如何从react-native中的另一个功能组件访问一个功能组件的状态?

时间:2020-09-20 09:48:25

标签: react-native

我想从MarkerView组件访问 ModalView的状态。实际上,当我单击 MarkerView 中的获取信息。按钮时,我想查看ModalView。我想从 MarkerView 组件设置{ setVisiblity(true)}。我该怎么办?

ModalView.js

printf()

MarkerView.js

const ModalView = () => {
    
    const [visiblity, setVisiblity] = useState(false);

    return (
        <Modal transparent={false} visible={visiblity} >

            <TouchableOpacity onPress={() => { setVisiblity(false)}}>
                <Text> Submit </Text>
            </TouchableOpacity>

        </Modal>
    )
}

App.js

const MarkerView = () => {

    return (
        // i want to set visiblity true from here
        <View>
            <TouchableOpacity onPress={() => { setVisiblity(true) }}> 
                    <Text>Get info.</Text>
            </TouchableOpacity>
        </View>
    )
}

1 个答案:

答案 0 :(得分:1)

您可以使用诸如contextAPIredux之类的状态管理,或者可以将状态置于更高阶的组件上,但这会导致一些道具钻探。

App.js

 const App = () => {
    const [visiblity, setVisiblity] = useState(false);
    
      return (
    
          <View>
            <Marker visiblity={visiblity} onChangeVisiblity={(val) => setVisiblity(val)}/>
            <ModalVIew visiblity={visiblity} onChangeVisiblity={(val) => setVisiblity(val)}/>
    
          </View>
      )
    }

MarkerView.js

const MarkerView = ({visiblity, onChangeVisiblity: changeVisiblity}) => {

    return (
        <View>
            <TouchableOpacity onPress={() => changeVisiblity(true)}> 
                    <Text>Get info.</Text>
            </TouchableOpacity>
        </View>
    )
}

ModalView.js

const ModalView = ({visiblity, onChangeVisiblity:changeVisiblity}) => {
    
    const [visiblity, setVisiblity] = useState(false);

    return (
        <Modal transparent={false} visible={visiblity} >

            <TouchableOpacity onPress={() => changeVisiblity(false)}>
                <Text> Submit </Text>
            </TouchableOpacity>

        </Modal>
    )
}