在运行时在 React 组件之间发送数据
Send data between React components during runtime
我正在开发我的第一个 React 应用程序,目前面临的问题是必须在运行时在多个组件之间交换数据。我已经找到了各种方法来解决这个问题,但对于我应该遵循哪种方法以及哪种方法最有意义感到非常困惑。
需求一:父组件向子组件发送数据(while运行)
数据应该从父组件发送到子组件。例如,这可以是输入字段的内容。我目前为此使用参考 API。在父组件中,我创建了对子组件的引用,并使用回调 (onChange) 调用子组件的函数(带参数)。
const map = useRef();
[...]
<Map ref={map} />
[...]
<input type="text" placeholder="Enter location" onChange={enterLocation} />
[...]
function enterLocation(event) {
map.current.locationSearch(location); // Function of the child component
}
需求2:从子组件向另一个子组件发送数据(while 运行)
要在两个子组件之间发送数据。我找到了多种解决方法:Redux、Context API 以及 Reference API。我的想法是先将数据发送到父组件,然后通过引用将其发送到另一个子组件。但是,这对我来说似乎不必要地复杂。
通常最简单的解决方案是最好的。
对于第一个示例,您可以将数据从 parent 组件发送到 children 组件作为道具:
function Parent() {
const data = 'some_string';
return <div>
<Child title={data} />
<div>Other component</div>
</div>
}
function Child(props) {
return <span>{props.title}</span>
}
对于第二个要求你可以使用状态,如果两个 children 使用一些状态,你可以在 parent:
function Parent() {
const [state, setState] = useState('');
return <>
<Input value={state} setValue={setState} />
<Length str={state} />
</>
}
function Input(props) {
return <input value={props.value} onChange={(e) => props.setValue(e.target.value)} />;
}
function Length(props) {
return <div>You insert string with length: {props.str.length}</div>
}
我正在开发我的第一个 React 应用程序,目前面临的问题是必须在运行时在多个组件之间交换数据。我已经找到了各种方法来解决这个问题,但对于我应该遵循哪种方法以及哪种方法最有意义感到非常困惑。
需求一:父组件向子组件发送数据(while运行)
数据应该从父组件发送到子组件。例如,这可以是输入字段的内容。我目前为此使用参考 API。在父组件中,我创建了对子组件的引用,并使用回调 (onChange) 调用子组件的函数(带参数)。
const map = useRef();
[...]
<Map ref={map} />
[...]
<input type="text" placeholder="Enter location" onChange={enterLocation} />
[...]
function enterLocation(event) {
map.current.locationSearch(location); // Function of the child component
}
需求2:从子组件向另一个子组件发送数据(while 运行)
要在两个子组件之间发送数据。我找到了多种解决方法:Redux、Context API 以及 Reference API。我的想法是先将数据发送到父组件,然后通过引用将其发送到另一个子组件。但是,这对我来说似乎不必要地复杂。
通常最简单的解决方案是最好的。
对于第一个示例,您可以将数据从 parent 组件发送到 children 组件作为道具:
function Parent() {
const data = 'some_string';
return <div>
<Child title={data} />
<div>Other component</div>
</div>
}
function Child(props) {
return <span>{props.title}</span>
}
对于第二个要求你可以使用状态,如果两个 children 使用一些状态,你可以在 parent:
function Parent() {
const [state, setState] = useState('');
return <>
<Input value={state} setValue={setState} />
<Length str={state} />
</>
}
function Input(props) {
return <input value={props.value} onChange={(e) => props.setValue(e.target.value)} />;
}
function Length(props) {
return <div>You insert string with length: {props.str.length}</div>
}