React Native:从子组件更改父级的状态或属性

时间:2017-07-24 10:21:40

标签: javascript android reactjs react-native state

假设我有一个名为HomeScreen的类,它有Location,Person是Components:

HomeScreen contains the component Location:

constructor(props){
      super(props);
      this.state = {
          location: '',
      }
    }

    export default class HomeScreen extends Component {
    ...
      render() {
        const { navigate } = this.props.navigation;
        return (
                 <Location 
                    navigator={this.props.navigation}
                    ></Location>
                 <Person location={this.state.location} />
        )}
    }

位置等级:

export default class LocationSelector extends Component{
        constructor(props){
        super(props);
        this.state = {
            location: '',
            region: '',
        }
    }

   onSelect = fullLocation => {
    var location = fullLocation.location;
    this.setState({location: location});
   }

    render(){
        return (
                  <View>
                     <TouchableOpacity
                     onPress={() => this.props.navigator.navigate('Location',{ onSelect: this.onSelect })}>
                     </TouchableOpacity>
                   </View>
             )
   }
}

人类:

class  Person extends Component{

  constructor(props){
    super(props);
    this.state={
      distance: 2,
    }
  }

    static defaultProps = {
      location:  '',
    }

  componentWillReceiveProps (nextProps) {
    this.setState({distance: 4});
  }

  render () {
    return <Text>Person: {this.props.location} distance : {this.state.distance}</Text>;
  }
}

代码说明: explaining the long codes

HomeScreen (state =&gt; location)是第一个看到的类,从这里添加位置(state =&gt; location)组件。 现在在Location类中,位置状态已初始化。 在 Person (prop =&gt; location,state =&gt; distance)类中,我需要该值来重新呈现Person组件以动态提供一个名为distance的状态。

我的问题是如何从Location组件获取值并将其设置为HomeScreen状态并将相同的值传递给Person类?

我正在使用 componentWillReceiveProps ()来重新加载Person Component。

0 个答案:

没有答案