3 回答

TA貢獻1936條經驗 獲得超7個贊
在 React 中使用鉤子更改子組件的父組件狀態
子組件保存輸入字段,我們將把輸入字段值發送到父組件。因此,讓我們先創建父組件。
父.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 屬性設置為子組件。下一步是創建子組件。
兒童.js
function Child(props) {
return(
<input onChange={(e)=>{props.onChangeName(e.target.value)}} />
<input onChange={(e)=>{props.onChangePassword(e.target.value)}} />
)}
在上面的代碼中,我們創建了函數句柄更改,該函數將值通過 props.onChange 傳遞到我們的父組件。

TA貢獻1884條經驗 獲得超4個贊
為此,您必須按如下方式實現它。
父母:
<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貢獻1880條經驗 獲得超4個贊
句柄更改函數在哪里?在輸入組件中,在 “組件旁邊,應包含 .onSubmit={props.onSubmit}
onChange={props.onChange}
添加回答
舉報