gpt4 book ai didi

javascript - 如何在 react Hook 中更新状态的单个属性?

转载 作者:行者123 更新时间:2023-12-05 09:12:16 26 4
gpt4 key购买 nike

我正在尝试更改状态 Hook ,但出现此错误...我知道另一种更改方法,但它应该适用于扩展语法,对吗?

export default function App() {
const [state, setState] = {
sld_url: "",
geojson_url: "",
}

const handleSldUrlChange = event => {
setState({...state, sld_url: event.target.value})
}

return (
<TextField
label="SLD URL"
value={state.sld_url}
className={classes.textField}
onChange={handleSldUrlChange}
margin="normal"
variant="outlined"
/>
);
}

最佳答案

首先你需要useState :

const [state, setState] = useState({
sld_url: "",
geojson_url: "",
})

handleSldUrlChange 函数中,您可以使用自定义回调来更新状态

const handleSldUrlChange = event => {
setState(prev => {...prev, sld_url: event.target.value})
//or
//setState({...state,sld_url: event.target.value})
}

演示:https://stackblitz.com/edit/react-mv8lsz

关于javascript - 如何在 react Hook 中更新状态的单个属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58755036/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com