【发布时间】:2019-10-22 23:06:15
【问题描述】:
我想做一个小反应应用程序来保存短文本条目。该应用程序显示所有已发布的条目,用户可以通过编写和发布来添加新条目。
应用程序具有string-array (string[]) 类型。数组中的每一项都是一个条目,必须显示在前端条目列表中。
我知道我不能 push 到数组,因为这不会直接改变状态(并且反应没有注意到它必须重新渲染)。所以我用这种方式来获得新的状态:oldState.concat(newEntry)。但是 React 不会重新渲染它。
这是我的整个反应代码:
function App() {
const [entries, setEntries] = useState([] as string[])
const publish = (entry: string) => {
setEntries(entries.concat(entry))
}
return (
<div>
<Entries entries={entries} />
<EntryInput publish={publish} />
</div>
)
}
function Entries(props: { entries: string[] }) {
return (
<div className="entries">
{props.entries.map((v, i) => { <EntryDisplay msg={v} key={i} /> })}
</div>
)
}
function EntryInput(props: { publish: (msg: string) => void }) {
return (
<div className="entry-input">
<textarea placeholder="Write new entry..." id="input-new-entry" />
<button onClick={(e) => { props.publish((document.getElementById("input-new-entry") as HTMLTextAreaElement).value) }}>Publish</button>
</div>
)
}
function EntryDisplay(props: { msg: string }) {
return (
<div className="entry">{props.msg}</div>
)
}
const reactRoot = document.getElementById("react-root")
ReactDOM.render(<App />, reactRoot)
【问题讨论】:
标签: reactjs typescript