【发布时间】:2020-03-06 19:03:28
【问题描述】:
我正在使用 React 钩子来设置状态。有一个父组件有多个子组件。父组件拥有状态,并将函数传递给子组件以回调的方式更新其状态。
子组件都是一样的,只是接收到不同的函数回调来更新父组件中的相关状态。
我的问题是,我可以在父级中编写一个handleChange 函数,以允许我使用此函数回调结构在父级中设置多个状态值吗?
父组件:
import React, { useState } from 'react'
import Control from './Control'
const Sort = () => {
const [controlUpValues, setControlUpValues] = useState([])
const [controlDownValues, setControlDownValues] = useState([])
const handleControlUpChange = values => {
setControlUpValues(values)
}
const handleControlDownChange = values => {
setControlDownValues(values)
}
return
<>
<Control
setControlItems={handleControlUpChange}
/>
<Control
setControlItems={handleControlDownChange}
/>
</>
)
}
export default Sort
子组件:
import React, { useState } from 'react'
import { Button, TextField } from '@material-ui/core'
function Control({ setControlItems }) {
const [controlInputValues, setControlInputValues] = useState([])
const [inputRef, setInputRef] = useState([])
const [inputValues, setInputValues] = useState([])
const handleValueChange = () => setInputValues(inputRef.value)
const addValuesToItems = () => {
setControlItems(inputValues)
}
return (
<div>
<TextField
inputRef={ref => setInputRef(ref)}
value={controlInputValues ? controlInputValues : ''}
onChange={handleValueChange}
/>
<Button
onClick={addValuesToItems}
>
Add
</Button>
</div>
)
}
export default Control
【问题讨论】:
标签: javascript reactjs ecmascript-6 react-hooks