首页 > 解决方案 > 使用 Hooks 将数据从子组件传递到父组件

问题描述

我想从 Child 组件传递 myVarible 并在 App(父)组件中检索它,然后将其放在 initialLang 属性上。

家长:

imports ...

// Here there is not "class App extends React.Component {" !!!

const App = () => (
    <Provider store={store}>
        <I18n translations={translations} initialLang="en" fallbackLang="en"></I18n>
    </Provider>
);

export default App;

孩子 :

imports ...

// Here there is not "class Child extends React.Component {" !!!

const ChildInner = ({context}) => (  
    {
        <View style={{flexDirection: "row"}}>   
            <Picker 
                onValueChange={(itemValue, itemIndex) => {
                    if ( itemIndex == 0 ) {
                        myVariable = 'en';
                    } else if ( itemIndex == 1 ) {
                        myVariable = 'fr';
                    }
                }} 
            >
                <Picker.Item label="English" value="en" />
                <Picker.Item label="french" value="fr" />
            </Picker>
        </View>
    }
);

const Child = (context) => (
    ...
);

Child.propTypes = {
    ....
};

Child.contextTypes = {
    t: PropTypes.func.isRequired,
};

export default Child;

我不知道在使用钩子时如何使用道具或状态来做到这一点。谢谢你的帮助。

标签: reactjsreact-hooksstatenative

解决方案


在家长中:

const [myVariable, setMyVariable] = useState('');
<ChildElement setMyVariable={setMyVariable}/>

在孩子

onClick={() => {props.setMyVariable('test123')}}

推荐阅读