3 回答

TA貢獻(xiàn)1936條經(jīng)驗(yàn) 獲得超7個(gè)贊
在 React 中使用鉤子更改子組件的父組件狀態(tài)
子組件保存輸入字段,我們將把輸入字段值發(fā)送到父組件。因此,讓我們先創(chuàng)建父組件。
父.js
import Child from "./Child";
function Parent() {
const [name, setName] = useState("");
const [password, setPassword] = useState("");
const onChangeName=(newValue)=>{
setName(newValue);
}
const onChangePassword=(value)=>{
setPassword(value);
}
// We pass a callback to Child
return (
<Child onChangeName={onChangeName} onChangePassword={onChangePassword} />;
)}
如您所見,我們將 onChange 屬性設(shè)置為子組件。下一步是創(chuàng)建子組件。
兒童.js
function Child(props) {
return(
<input onChange={(e)=>{props.onChangeName(e.target.value)}} />
<input onChange={(e)=>{props.onChangePassword(e.target.value)}} />
)}
在上面的代碼中,我們創(chuàng)建了函數(shù)句柄更改,該函數(shù)將值通過 props.onChange 傳遞到我們的父組件。

TA貢獻(xiàn)1884條經(jīng)驗(yàn) 獲得超4個(gè)贊
為此,您必須按如下方式實(shí)現(xiàn)它。
父母:
<Inputs
hasInputs={hasInputs}
onSubmit={this.handleSubmit}
thoughtProp={this.state.thought}
onChange={(event, index) => this.handleChange(event, index)}
/>;
孩子:
import React from 'react';
import { Input } from '../Input.js';
export const Inputs = (props) => {
return (
<form className="flex-item-main form" onSubmit={props.onSubmit}>
<ol>
{props.thoughtProp.map((input, index) => (
<Input
type="text"
onSubmit={props.onSubmit}
key={index}
value={input}
onChange={(event, index) => props.onChange(event, index)}
className="textInputs"
/>
))}
{props.hasInputs ? (
<input
className="submitThoughts"
type="submit"
value="Submit Thought!"
/>
) : null}
</ol>
</form>
);
};

TA貢獻(xiàn)1880條經(jīng)驗(yàn) 獲得超4個(gè)贊
句柄更改函數(shù)在哪里?在輸入組件中,在 “組件旁邊,應(yīng)包含 .onSubmit={props.onSubmit}
onChange={props.onChange}
添加回答
舉報(bào)