小编Car*_*lla的帖子

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

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

这是我的主要组成部分

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>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

这是我的孩子组成部分

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 …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs react-native

0
推荐指数
1
解决办法
121
查看次数

标签 统计

javascript ×1

react-native ×1

reactjs ×1