![](/img/trans.png)
[英]Updating Parent component state from Child component TextInput in React Native
[英]React Native - Sets the state of the child component directly on the parent component
我想問個問題。 在我遇到的情況下,我有很多內部使用 state 的組件。 所以我沒有在父組件中聲明該組件的state,因為我不希望父組件出現多個狀態。 我的問題是我可以在父組件中設置每個子組件的 state 值嗎?
這是我想要做的代碼示例:
import React from 'react';
import {Switch} from 'react-native';
const Parents = () => {
{/**
Can I set state (setIsEnabled) directly on the parent component?
For example:
<Child active={true} onValueChange={() => setIsEnabled(!isEnabled)} />
*/}
return (
<Child active={true} />
);
}
const Child = ({active}) => {
const [isEnabled, setIsEnabled] = React.useState(active);
return (
<Switch
trackColor={{
false: 'rgba(0, 0, 0, 0.12)',
true: 'rgba(66, 133, 244, 0.54)',
}}
thumbColor={isEnabled ? 'rgb(66, 133, 244)' : 'rgb(250, 250, 250)'}
ios_backgroundColor="rgba(0, 0, 0, 0.12)"
onValueChange={() => setIsEnabled(!isEnabled)}
value={isEnabled}
/>
);
}
我想這就是你要找的
import React from 'react';
import {Switch} from 'react-native';
const Parents = () => {
{/**
Can I set state (setIsEnabled) directly on the parent component?
For example:
<Child active={true} onValueChange={() => setIsEnabled(!isEnabled)} />
*/}
return (
<Child active={true} />
);
}
const Child = (props) => {
const [isEnabled, setIsEnabled] = React.useState(props.active);
return (
<Switch
trackColor={{
false: 'rgba(0, 0, 0, 0.12)',
true: 'rgba(66, 133, 244, 0.54)',
}}
thumbColor={isEnabled ? 'rgb(66, 133, 244)' : 'rgb(250, 250, 250)'}
ios_backgroundColor="rgba(0, 0, 0, 0.12)"
onValueChange={() => setIsEnabled(!isEnabled)}
value={isEnabled}
/>
);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.