是否可以在React Native中更改其无状态组件子级的父级状态?

时间:2018-03-13 07:36:34

标签: javascript reactjs react-native

在我的App.js中,我初始化了一些类似的状态,

export default class App extends React.Component {
  constructor(){
    super();
     this.state = {
            myfirststate: '',
            mysecondstate: '',
     }    
    }
    ...
   }

现在我有一个ChildComponent.js,它是无状态的,就像这样有一个按钮,点击后,将myfirststate的状态从null更改为hello

 export default class ChildComponent extends React.Component {
   render() {
    return (
      <View>
        <Button
          title="clickme"
          onPress={() => 
             this.setState({myfirststate: "hello"})
        />
      </View>
      );
     }
    }

有可能做这样的事吗?我一直认为我必须将状态值作为一个函数传递给一个函数,而这个函数从父组件传递给子组件,而不是像这样。

App.js

 export default class App extends React.Component {
  constructor(){
   super();
    this.state = {
        myfirststate: '',
        mysecondstate: '',
     }    
   }

 functiontopassvalues(values) {
    this.setState({
        myfirststate: values
    })
   }
   <ChildComponent functiontopassvalues={this.functiontopassvalues} />
  }

ChildComponent.js我会做这样的事情

    export default class ChildComponent extends React.Component {
      render() {
        return (
         <View>
           <Button
            title="clickme"
             onPress={() => 
             {this.props.functiontopassvalues("hello")}
        />
      </View>
      );
     }
    }

我希望我有意义,请让我知道这样做的正确方法是什么,为什么会这样。此外,它是否同时适用于native和react.js?

2 个答案:

答案 0 :(得分:1)

您的方法是正确的,但您的子组件知道需要将哪些值传递给父级,从技术上讲它是正确的,但它不可扩展。您可以将onPress句柄传递给子组件,并在父组中将您想要的任何值传递给父状态。

考虑以下示例

export default class App extends React.Component {
 constructor(){
  super();
  this.state = {
    myfirststate: '',
    mysecondstate: '',
  }    
 }

 functiontopassvalues= (values) => {
  this.setState({
    myfirststate: values
  });
 }
 <ChildComponent title="click me" onPress={() => this.functiontopassvalues('hello')} />
}

可以通过一些更改使子组件可扩展

export default class ChildComponent extends React.Component {
  render() {
    return (
     <View>
       <Button
         title={this.props.title}
         onPress={this.props.onPress}
       />
     </View>
   );
 }
}

使用@Sam指定的任何状态管理工具总是更好。他们非常有帮助。

答案 1 :(得分:0)

你解决这个问题的方法是公平和正确的,但它不一定是可扩展的,你是正确的,你不能改变孩子的父母状态。

我建议您查看ReduxMobXApollo Link State这些试图解决国家管理永恒问题的工具。