![](/img/trans.png)
[英]How to pass down event from parent to child in react with functional components?
[英]Clear React child input value from parent using functional components
我想在設置 redux state 后從父級清除子功能組件
這是我的代碼
const ParentContainer = (props) => {
const onKeyDown = (keyPressed) => {
if (keyPressed.key === 'Enter' && keyPressed.currentTarget.value.length > 0) {
props.addMail(keyPressed.currentTarget.value);
keyPressed.target.value = ''
}
}
return (<Child onKeyPressDown={onKeyDown} />)
}
在子組件上
const Child = (props) => {
return (<Input placeholder="Add text list"
fluid onKeyDown={
props.onKeyPressDown
}
/>)
}
export default Child
實際上,當我按下enter
鍵時,文本會保留下來,我想將其刪除。
我在父組件中嘗試了keyPressed.target.value = ''
但它不起作用
您需要在 Parent 組件中引入狀態。 然后將狀態值傳遞給輸入,並在輸入更改時提供 onChange 處理程序。 這稱為受控組件,您可以在此處閱讀有關它的更多信息。
https://reactjs.org/docs/forms.html#controlled-components
const ParentContainer = (props) => {
const [value, setValue] = useState('');
const onKeyDown = (event) => {
if (event.key === 'Enter' && event.currentTarget.value.length > 0) {
props.addMail(event.currentTarget.value);
setValue('');
}
};
return <Child value={value} setValue={setValue} onKeyPressDown={onKeyDown} />;
};
const Child = (props) => {
return (
<Input
fluid
value={props.value}
onChange={(event) => props.setValue(event.target.value)}
onKeyDown={props.onKeyPressDown}
placeholder="Add text list"
/>
);
};
handleReset = () => {
Array.from(document.querySelectorAll("input")).forEach(
input => (input.value = "")
);
this.setState({
itemvalues: [{}]
});
};
我找到了答案,希望它能幫助https://www.freecodecamp.org/news/how-to-clear-input-values-of-dynamic-form-in-react/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.