【发布时间】:2020-08-16 08:38:02
【问题描述】:
基本上我想让 Parent 元素控制其子元素的值。通过之前使用 React 输入,我知道您需要传递一个 onChange 属性,以便 Parent 可以更新它传递给其子级的值。
我已将 value 和 onChange 属性设为可选,因为我还想支持您将 Child 用作不受控制的输入的情况。
Child 的不受控制和未处理的受控变体都有效。但是处理的受控变体没有。
任何想法如何让它发挥作用?我已将下面的 JSFiddle 与显示我的问题的最小示例链接:
https://jsfiddle.net/numberjak/wufdh0ys/3/
代码:
const Parent = () => {
const [parentValue, setParentValue] = React.useState(0);
return (
<div>
Should act like uncontrolled input (i.e. value should change) [WORKS]
<Child />
Should act like controlled input (i.e. value should change because onChange handler passed in) [DOESN'T WORK]
<Child value={parentValue} onChange={setParentValue} />
Should act like controlled input, except no onChange handler means value shouldn't change [WORKS]
<Child value={5} />
</div>
);
};
const Child = ({value, onChange}) => {
const [childValue, setChildValue] = React.useState(value !== undefined ? value : 0);
const handleOnChange = (newValue) => {
if (value === undefined) {
setChildValue(newValue);
}
if (onChange !== undefined) {
onChange(newValue);
}
};
return (
<GrandChild value={childValue} onChange={handleOnChange} />
);
};
const GrandChild = ({value, onChange}) => {
const handleOnClick = () => {
onChange(value + 1);
};
return (
<div className="grand-child" onClick={handleOnClick}>{value}</div>
);
};
ReactDOM.render(<Parent />, document.querySelector("#app"))
【问题讨论】:
标签: javascript reactjs react-hooks jsx