reactjs - 使用 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;
我不知道在使用钩子时如何使用道具或状态来做到这一点。谢谢你的帮助。
解决方案
在家长中:
const [myVariable, setMyVariable] = useState('');
<ChildElement setMyVariable={setMyVariable}/>
在孩子
onClick={() => {props.setMyVariable('test123')}}
推荐阅读
- angular - 角材料垫卡未正确显示拉丁字母字符
- powershell - 使用 Powershell 修改 SCCM 应用程序部署失败
- ios - 我的视图是透明的,如何使组件不透明
- laravel - .htaccess - 从代理重定向中排除特定的 URL 和目录
- xamarin.forms - 在 xamarin.forms 中为 android 自定义标签页
- python - Python/API:处理服务器不返回的错误
- android - 为 Google 登录自定义新的 Android MaterialButton
- prolog - prolog - 生成整数“unwindably”
- php - 根据季节更改着陆点 (PHP)
- vba - Microsoft Access VBA:找不到项目或库