Javascript 在React Native中将道具传递到状态?

Javascript 在React Native中将道具传递到状态?,javascript,reactjs,react-native,Javascript,Reactjs,React Native,我在主屏幕上有一个按钮,用于切换AlertBar中的文本 因此,当我按下一个按钮时,AlertBar中的文本应根据标记的状态而变化。目前当我按下按钮时,什么都没有发生。。。我不知道为什么 这是我的主屏幕: class Home extends Component { constructor(props) { super(props); this.state = { isParked: false }; }

我在主屏幕上有一个按钮,用于切换AlertBar中的文本

因此,当我按下一个按钮时,
AlertBar
中的文本应根据标记的状态而变化。目前当我按下按钮时,什么都没有发生。。。我不知道为什么

这是我的主屏幕:

class Home extends Component {

    constructor(props) {
      super(props);
      this.state = {
          isParked: false
      };    
  }


    pressPark = () => this.setState({isParked:true})

    render() {
        console.ignoredYellowBox = ['Remote debugger'];

        return (

            <View>
                    <View>
                        <AlertBar isParked={this.state.isParked}/>
                    </View>

                    <View style={styles.parkButton}>
                        <Button title='PARK' onPress={this.pressPark} color='green'/>
                    </View>
            </View>

            );
        }
    }
class Home扩展组件{
建造师(道具){
超级(道具);
此.state={
标记为:假
};    
}
按Park=()=>this.setState({isParked:true})
render(){
console.ignoredYellowBox=[“远程调试器”];
返回(
);
}
}
以下是我的AlertBar.js:

class AlertBar extends Component {

        state = {
            region: 'Singapore',
            isParked: this.props.isParked,
            alertText: null
    }


...   some unrelated code ...

    componentDidMount() {

        if (this.state.isParked === false) {
                this.setState({alertText: "You're parking at"})} else if (this.state.isParked === true) {
                this.setState({alertText: "You're parked at"})}

        alert(this.state.alertText)
            }

    componentWillUnmount() {
        // some unrelated code
    }

    render() {

... some unrelated code...

        return(

                <View style={styles.container}>
                    <Text style={styles.welcomeText}>
                        {this.state.alertText}
                    </Text>
                    <Text style={styles.locationText}>
                        {this.state.region}
                    </Text>
                </View>
            )
    }
}
类AlertBar扩展组件{
状态={
地区:'新加坡',
isParked:this.props.isParked,
alertText:空
}
…一些不相关的代码。。。
componentDidMount(){
if(this.state.isParked==false){
this.setState({alertText:“您正在”})else if(this.state.isParked==true){
this.setState({alertText:“您停在了”})}
警报(this.state.alertText)
}
组件将卸载(){
//一些无关的代码
}
render(){
…一些不相关的代码。。。
返回(
{this.state.alertText}
{this.state.region}
)
}
}
我做错了吗?我不知道怎么了。。。。请帮忙!谢谢

使用

if (this.props.isParked === false)
而不是

if (this.state.isParked === false)

(而且不要直接将道具转移到状态,这也没有任何意义:)

此时,您的AlertBar组件没有处理任何道具更改

您需要做的是,在收到更新时将道具映射到状态

在AlertBar.js中添加这行代码,它将在收到更新时将isParked映射到state

componentWillReceiveProps(props) {
    this.setState({ isParked: props.isParked });
}