Lane :
私はセット状態にフックを反応させるの使用しています。複数の子要素を持つ親コンポーネントがあります。親コンポーネントが状態を有し、コールバックとしてその状態を更新するために、子コンポーネントに機能を渡します。
子コンポーネントが同じである、彼らは親に関連する状態を更新するために、異なる関数コールバックを受け取ります。
私の質問は、私は1つの書くことができている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
こうした:
あなたは状態を更新するための関数を含むオブジェクトを持つことができます。
親
import React, { useState } from 'react'
import Control from './Control'
const Sort = ({ classes }) => {
const [controlBoostValues, setControlBoostValues] = useState([])
const [controlBuryValues, setControlBuryValues] = useState([])
const functions = {
boost: setControlBoostValues,
bury: setControlBuryValues
}
const handleChange = (key, values) => functions[key](values);
return
<>
<Control
setControlItems={handleChange}
/>
<Control
setControlItems={handleChange}
/>
</>
)
}
子 :
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("boost" , inputValues)
}
return (
<div>
<TextField
inputRef={ref => setInputRef(ref)}
value={controlInputValues ? controlInputValues : ''}
onChange={handleValueChange}
/>
<Button
onClick={addValuesToItems}
>
Add
</Button>
</div>
)
}
export default Control