[英]Do I need to pass handler prop to child component?
I was thinking if I need to pass a handler of textfield/dropdown.我在想是否需要传递文本字段/下拉列表的处理程序。
const initialFormFields = {
name: '',
sample_select: '',
}
const [formFields, setFormFields] = useState(initialFormFields);
Parent Component父组件
const handleInputChange = event => {
event.persist();
const target = event.target;
const value = target.type === "checkbox"
? target.checked
: target.value;
setFormFields(formFields => ({...formFields,[target.name]: value}));
};
<form onChange={handleInputChange}>
<ChildComponent
name={formFields.name}
sample_select={formFields.sample_select}
/>
</form>
Child Component子组件
<TextField
name="name"
id="name"
value={props.name}
/>
<TextField
select
id="sample_select"
name="sample_select"
value={props.sample_select}
>
<MenuItem value="1">1</MenuItem>
<MenuItem value="2">2</MenuItem>
<MenuItem value="3">3</MenuItem>
</TextField>
On TextField Component it works, but in select component it doesn't trigger the handler在TextField组件上它可以工作,但在选择组件中它不会触发处理程序
Btw im using Material UI顺便说一句,我正在使用 Material UI
I think you should use "Select" component instead to make it work.我认为您应该使用“选择”组件来使其工作。 Example:例子:
<Select
value={props.sample_select}
onChange={handleInputChange}
>
<MenuItem value={10}>Ten</MenuItem>
<MenuItem value={20}>Twenty</MenuItem>
<MenuItem value={30}>Thirty</MenuItem>
</Select>
try this in parent:在父母中试试这个:
<form onChange={handleInputChange}>
<ChildComponent
name={formFields.name}
sample_select={formFields.sample_select}
handleInputChange={handleInputChange}
/>
</form>
in ChildComponent:在子组件中:
<TextField
name="name"
id="name"
value={props.name}
onChange={props.handleInputChange}
/>
<TextField
select
id="sample_select"
name="sample_select"
value={props.sample_select}
onChange={props.handleInputChange}
>
<MenuItem value="1">1</MenuItem>
<MenuItem value="2">2</MenuItem>
<MenuItem value="3">3</MenuItem>
</TextField>
Got It!知道了! Tried to console.log(event) and saw type of event.尝试 console.log(event) 并看到事件类型。 It's a click event, so I put onClick handler and it works!这是一个点击事件,所以我放置了onClick处理程序并且它起作用了! :D :D
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.