从子组件更改状态

时间:2018-07-13 01:07:11

标签: react-native

所以,我今天才弄清楚,只有在React Native应用程序中更改状态才会触发组件的重新渲染。我正在更改状态,但是我正在从子组件中进行操作,它似乎陷入了某种循环,() => { this.setState({current_time:'whatever'})似乎什么也没做。如何从App.js更改current_time的{​​{1}}的状态?

App.js

TimePicker.js

TimePicker.js

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      current_time:'initial time, unchanged in state',
    };
  }

  render() {
    let s = styles;

    return (
      <View style={s.contain}>
        <TimePicker />
        <ShowTime current_time={this.state.current_time} />
      </View>
    );
  }
}

ShowTime.js

class TimePicker extends Component {
    constructor(props){
        super(props);
    }

    render(){

        let s = styles;

        return(
            <TouchableOpacity>
                <View style={s.contain} onPress={
                    /* 

                    set this.state.current_time in parent to the actual current time
                    this.setState({current_time:'changed'}) seems to cause an infinite loop?

                    () => { this.setState({current_time:'changed'}) }  doesn't seem to do anything

                    */
                }>
                    <Text>I will change the time in state.</Text>
                </View>
            </TouchableOpacity>
        )
    }
};

2 个答案:

答案 0 :(得分:2)

在App.js中创建一个函数,并将其作为prop传递给TimePicker Component,此函数的目的应该是setState。例如 App.js

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      current_time:'initial time, unchanged in state',
    };
  }

currentTimeHandler = (newCurrentTime) => {
  this.setState({current_time: newCurrentTime});
}

  render() {
    let s = styles;

    return (
      <View style={s.contain}>
        <TimePicker getTime={ this.currentTimeHandler }/>
        <ShowTime current_time={this.state.current_time} />
      </View>
    );
  }
}

TimePicker.js

class TimePicker extends Component {
    constructor(props){
        super(props);
    }

    render(){

        let s = styles;

        return(
            <TouchableOpacity onPress={() => this.props.getTime('changes will be passed here')}>
                <View style={s.contain} >
                    <Text>I will change the time in state.</Text>
                </View>
            </TouchableOpacity>
        )
    }
};

答案 1 :(得分:0)

原因是setState仅在js文件中本地设置现有状态。那将是您的时间选择器。

在您的情况下,TimePicker是App的子级(或子分支)(您的应用程序通过当前版本存储您的状态,并且不会被子级更改)。您将需要创建两个函数,一个在TimePicker中,另一个在App中。 TimePicker将处理数据并通过prop发送,App将接收prop,然后将另一个函数触发到setState。

Pass data from child to parent in React

这是我能找到的最好的。

最好也阅读以下内容: https://reactjs.org/docs/react-component.html 它确实说,setState仅影响本地状态,您要设置的状态不是本地状态。