我正在button click
上动态添加列表。换句话说,我有一个text field
和button
单击按钮时,我正在input text
中添加list
。
我的问题是我想在同级之间共享数据。因为我有两个同级组件search
和ListItems
我想在items
个组件中发送list
来呈现列表
这是我的代码 https://codesandbox.io/s/sad-clarke-8dgtd
import React, { useState } from "react";
import "./styles.css";
const Search = () => {
const [state, setState] = useState("");
const [items, setItems] = useState([]);
const onChangeHandler = e => {
setState(e.target.value);
};
const addItems = () => {
setItems([...items, state]);
setState("");
};
return (
<>
<input type="text" value={state} onChange={onChangeHandler} />
<button onClick={addItems}>Add</button>
</>
);
};
const Item = ({ text }) => {
return (
<div>
{text}
<input type="checkbox" />
</div>
);
};
const ListItems = ({ items }) => {
return (
<ul>{items && items.map((item, key) => <Item key={key} item={item} />)}</ul>
);
};
export default function App() {
return (
<div className="App">
<Search />
<ListItems />
</div>
);
}
答案 0 :(得分:0)
您需要在App
组件级别定义状态,然后将该列表传递给每个子组件。看起来像这样:
export default function App() {
const [items, setItems] = useState([]);
return (
<div className="App">
<Search items={items} setItems={setItems} />
<ListItems items={items} setItems={setItems} />
</div>
);
}
然后,您可以从items
组件中删除Search
的定义。
正如Asaf Aviv所指出的,通常称为Lifting State Up
答案 1 :(得分:0)
Lift the state向上并通过道具
const Search = ({ addItem }) => {
const [input, setInpout] = useState("");
const onChangeHandler = e => {
setInpout(e.target.value);
};
const handleAddItem = () => {
addItem(input);
setInpout("");
};
return (
<>
<input type="text" value={input} onChange={onChangeHandler} />
<button onClick={handleAddItem}>Add</button>
</>
);
};
const Item = ({ text }) => (
<div>
<span>{text}</span>
<input type="checkbox" />
</div>
);
const ListItems = ({ items }) => (
<ul>
{items.map(text => (
<Item key={text} text={text} />
))}
</ul>
);
export default function App() {
const [items, setItems] = useState([]);
const addItem = text => setItems(prevState => [...prevState, text]);
return (
<div className="App">
<Search addItem={addItem} />
<ListItems items={items} />
</div>
);
}