如何从另一个组件调用并将值传递给函数
How to call and pass the value to function from another component
我试图在我的 CartList 组件中调用我的 ShoppingCartScreen 组件中的删除函数。我还想从 CartList 组件 class 传递值。当我尝试在我的 CartList class.
中调用添加时,我一直遇到问题
export default class ShoppingCartScreen extends Component {
remove = (qty) => {
let q = qty
if (q > 1) {
q = q - 1;
this.setState({ qty: q })
}
}
render() {
return (
<View>
<ScrollView backgroundColor='#bbb'>
<CartList
remove = {this.remove} />
</ScrollView>
</View>
)
}
export default class CartList extends Component {
render() {
return (
<View>
<TouchableOpacity onPress={this.props.add(this.state.qty)}>
<Icon
name="md-close"
size={25}
color='black'
style={{ height: 25, width: 25 }}
iconStyle={{ marginRight: 0 }}/>
</TouchableOpacity>
</View>
)
}
首先,您将 remove
传递给 CartList
,然后在内部调用 this.props.add
,因此您需要更改名称。其次,您需要将 this.props.remove
调用升级为箭头函数:
<TouchableOpacity onPress={() => this.props.remove(this.state.qty)}>
onPress
期望您传递一个要调用的函数。当组件被渲染时,this.props.add(this.state.qty)
立即被评估,因为它已经是一个函数调用。这就是在这种情况下必须使用箭头函数的原因。
我试图在我的 CartList 组件中调用我的 ShoppingCartScreen 组件中的删除函数。我还想从 CartList 组件 class 传递值。当我尝试在我的 CartList class.
中调用添加时,我一直遇到问题export default class ShoppingCartScreen extends Component {
remove = (qty) => {
let q = qty
if (q > 1) {
q = q - 1;
this.setState({ qty: q })
}
}
render() {
return (
<View>
<ScrollView backgroundColor='#bbb'>
<CartList
remove = {this.remove} />
</ScrollView>
</View>
)
}
export default class CartList extends Component {
render() {
return (
<View>
<TouchableOpacity onPress={this.props.add(this.state.qty)}>
<Icon
name="md-close"
size={25}
color='black'
style={{ height: 25, width: 25 }}
iconStyle={{ marginRight: 0 }}/>
</TouchableOpacity>
</View>
)
}
首先,您将 remove
传递给 CartList
,然后在内部调用 this.props.add
,因此您需要更改名称。其次,您需要将 this.props.remove
调用升级为箭头函数:
<TouchableOpacity onPress={() => this.props.remove(this.state.qty)}>
onPress
期望您传递一个要调用的函数。当组件被渲染时,this.props.add(this.state.qty)
立即被评估,因为它已经是一个函数调用。这就是在这种情况下必须使用箭头函数的原因。