如何从其他组件设置状态

时间:2019-08-01 06:56:26

标签: reactjs react-native

我正在尝试将功能组件的状态设置为App组件。但是它给了错误。请帮我解决一下这个。 预先感谢。

// APP组件

export default class App extends React.Component {
    onPasswordChange = (text) => {
        console.log("text: ", text);
        this.setState({name:text})
    } 

    onNameChange = (text) => {
        console.log("text: ", text);
    }

    state = {
        name: "",
        password:""
    }

    render() {
        return (
        <SafeAreaView style = {styles.container}>
            <TextField placeholder = "Email"  onTextChange = {(text) => this.onNameChange(text)}/>
            <TextField placeholder = "Password" isSecure = {true} onTextChange = {(text) => this.onPasswordChange(text)}/>
            <ButtonNormal title = "Login" onTouched = {()=> this.onPress()} />
        </SafeAreaView>
           );
         };
}

// TextField组件。

const TextField = (props) => {
    return (
    <TextInput placeholder = {props.placeholder} style = {Styles.textField} secureTextEntry={props.isSecure} onChangeText={(text) => props.onTextChange(text) }/>
    );
};

Error showing like this.

1 个答案:

答案 0 :(得分:0)

请勿在子组件中触发该函数,因为您没有向其添加其他数据,因此请在设置数据之前对其进行操作。只需通过prop设置函数,因为它已经与父箭头函数绑定了。

const TextField = (props) => {
    return (
    <TextInput placeholder = {props.placeholder} style = {Styles.textField} secureTextEntry={props.isSecure} onChangeText={props.onTextChange}/>
    );
};