我在子组件中有两个文本输入。第一个工作正常,那就是通过升高状态然后降低状态来交换输入值child-> parent-> child。
但是,即使代码相同,它也不适用于第二个组件。有什么想法吗?
我得到:undefined不是函数(评估'this.props.emailTwoUp(email)')
父代码:
emailOneStateChange(value){
this.setState({emailone: value});
}
emailTwoStateChange(value){
this.setState({emailtwo: value});
}
render() {
return (
<View style={styles.container}>
<EmailInput
emailOneUp={this.emailOneStateChange}
emailTwoUp={this.emailTwoStateChange}
emailOneDown={this.state.emailone}
emailTwoDown={this.state.emailtwo}
/>
</View>
);
}
子代码:
export default class EmailInput extends Component {
constructor(props) {
super(props);
this.emailOneUp = this.emailOneUp.bind(this);
this.emailTwoUp = this.emailTwoUp.bind(this);
}
emailOneUp(email) {
this.props.emailOneUp(email);
}
emailTwoUp(email) {
this.props.emailTwoUp(email);
}
render() {
return (
<View>
<TextInput
onChangeText={this.emailOneUp}
value={this.props.emailOneDown}
/>
<TextInput
onChangeText={this.emailTwoUp}
value={this.props.emailTwoDown}
/>
</View>;
);
}
}
答案 0 :(得分:0)
您的问题似乎是功能绑定之一。将函数传递给子组件时,您需要确保将其绑定到父组件,否则它将无法按预期工作,并且this
会丢失其上下文,从而给您带来错误。
在一个简单的示例中,使用您的EmailInput
组件。父组件使用箭头功能绑定其功能。我们还添加了一个按钮,以便我们可以轻松地检查状态。
import * as React from 'react';
import { Text, View, StyleSheet, Button } from 'react-native';
import { Constants } from 'expo';
import EmailInput from './EmailInput'
export default class App extends React.Component {
state = {
emailone : '',
emailtwo: ''
}
// bind these functions to this component
// using arrow functions
emailOneStateChange = (value) => {
this.setState({emailone: value});
}
emailTwoStateChange = (value) => {
this.setState({emailtwo: value});
}
onPress = () => {
alert(JSON.stringify(this.state))
}
render() {
return (
<View style={styles.container}>
<EmailInput
emailOneUp={this.emailOneStateChange}
emailTwoUp={this.emailTwoStateChange}
emailOneDown={this.state.emailone}
emailTwoDown={this.state.emailtwo}
/>
<Button onPress={this.onPress} title={'press me'} />
</View>
);
}
}
然后在EmailInput
组件中,我们再次使用箭头函数来绑定函数,这意味着我们不需要在构造函数中绑定函数。实际上,除非确实需要,否则我们可以取消构造函数。
export default class EmailInput extends React.Component {
// using arrow functions allows us to get rid of an unnecessary constructor
emailOneUp = (email) => {
this.props.emailOneUp(email);
}
emailTwoUp = (email) => {
this.props.emailTwoUp(email);
}
render() {
return (
<View>
<TextInput
placeholder={'email one'}
onChangeText={this.emailOneUp}
value={this.props.emailOneDown}
/>
<TextInput
placeholder={'email two'}
onChangeText={this.emailTwoUp}
value={this.props.emailTwoDown}
/>
</View>
);
}
}
现在,这些函数可以按预期方式工作,并将值传递给子组件或从子组件传递值。这是我制作的一种小吃,显示出它的功效。
https://snack.expo.io/@andypandy/binding-functions-pass-to-child