javascript - 这是在react.js中设置父组件状态的正确方法吗

标签 javascript reactjs react-native

我从子组件中设置了主组件的所有上下文,它工作正常,但我不知道这是否正确

这是我的主要组件

import Child from "./apps/child";

export default class NewTest extends Component {

  constructor(){
    super();
    this.state={
      one:1,
    }
  }

  render() {
    return (
      <View style={styles.container}>

        <Text>{this.state.one}</Text>

        <Child root={this}/>  //<----- Here i set all the context of my main Component to the child component 

        <TouchableOpacity onPress={()=>console.log(this.state.one)}>  
          <Text>Touch</Text>
        </TouchableOpacity>

      </View>
    );
  }
}

这是我的子组件

export default class Child extends Component{

  constructor(props){
    super(props);

    this.parent=this.props.root;
  }

  render(){
    return(
      <View>
        <TouchableOpacity onPress={()=>{
          this.parent.setState({one:this.parent.state.one+1}) // <- if you see here i change the state of the parent, and it work fine
        }}>
          <Text>Sum to Parent</Text>
        </TouchableOpacity>
      </View>
    )
  }
}

所有这些都有效,但是这是正确的方法吗?

最佳答案

不,不是。如果您想更改父组件的状态,您应该将回调函数作为 prop 发送给子组件,然后调用它。例如,您可以在 NewTest 中有一个函数:

increaseOne(){
    this.setState({one:this.state.one+1})
}

然后,用 prop 将其发送给 child :

<Child increaseOne={this.increaseOne.bind(this)}/>

最后在子onPress中调用它:

<TouchableOpacity onPress={this.props.increaseOne}>

如果应用程序变得太复杂,您可以使用 Redux .

关于javascript - 这是在react.js中设置父组件状态的正确方法吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40460085/

相关文章:

javascript - 如何获取包含表单中可用的所有输入标签的列表

javascript - 如何在Next js上将数据从express服务器发送到客户端?

javascript - API调用时React JS(休息时的管理员)错误

twitter-bootstrap - React-Bootstrap下拉按钮pullRight/Left

react-native - 当键盘显示在 react native 中时如何使 touchables 可触摸

javascript - 在 javascript 函数中对数据库执行 php 插入

javascript - http请求的串行执行

javascript - 为什么我在 React 应用程序中失去了登录信息?

javascript - 防止Reactjs中的按钮自动提交

android - 如何修复 facebook::react::Value::toJSONString 中的崩溃