[英]Passing Props With Input - React
在子组件中,我有 state 来存储输入。
我的目标是将输入 state 传递给父组件。
//Child component
const [userInput, setUserInput] = useState("");
<TextField value={input} onInput={e => setInput(e.target.value)} />
我尝试创建一个 function 以在父级 function 中的输入上调用,但我似乎无法获得传递的值“输入”。 这样做的正确方法是什么? 谢谢!
您可以将 state 移动到父组件。 然后将道具从孩子传递给父母。
function Child({
...rest
}) {
return <TextField {...rest} />
}
function Parent() {
const [input, setInput] = useState(''); // '' is the initial state value
return (
<Child value={value} onInput={e => setInput(e.target.value)} />
)
}
你走对了。 您可以传递 function 以从子级获取数据到父级。 检查这个例子:
import { useState } from "react";
import "./styles.css";
export default function App() {
const [text, setText] = useState("");
const getInput = (t) => {
console.log(t);
setText(t);
};
return (
<div className="App">
<Component getInput={getInput} value={text} />
<p>{text}</p>
</div>
);
}
const Component = ({ getInput, value }) => {
return (
<>
<h1> Test </h1>
<input type="text" value={value} onChange={(e) => getInput(e.target.value)}></input>
</>
);
};
父App
正在通过 function getInput
从子Component
检索文本。 您只需要决定要引爆的事件。 当然,这是针对input
而不是 TextField。 我认为您正在使用 React Material UI 中的 TextField,如果是这种情况,您可以查看文档以了解如何触发事件。
我终于想通了。
// This is in the parent component
const [userInput, setUserInput] = useState("");
// Step 1: Create a function that handles setting the state
const inputHandler = (userInput) => {
setUserInput(userInput);
}
<PhaseTwoTemplate onInput={inputHandler} />
//Step 2: Add a function that calls the handler
...
// This is the child component PhaseTwoTemplete.js
const [input, setInput] = useState("");
// This second state holds the input data for use on child component
// It also is an easy way to hold the data for the parent function.
<TextField
onChange={e => setInput(e.target.value)}
value={input}
onInput={onInputHandler}
/>
// Step 3: Pass the user input to the parent
const onInputHandler = () => {
props.onInput(input);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.