我用SetState更改父級的狀態有問題。首先,我有我的RootView.jsx有:SetState to parent
constructor(props) {
super(props);
this.state = {
sizes: [
{label: "90x50mm", isChecked: false, number: 10},
{label: "85x55mm", isChecked: false, number: 12}
],
ratings: [
{label: "OneStar", isChecked: false, imgSrc: 'images/Rating1Star.svg', counter: 22},
{label: "TwoStars", isChecked: false, imgSrc: 'images/Rating2Stars.svg', counter: 18},
{label: "ThreeStars", isChecked: false, imgSrc: 'images/Rating3Stars.svg', counter: 34},
{label: "FourStars", isChecked: false, imgSrc: 'images/Rating4Stars.svg', counter: 27}
],
favorites: [
{label: "Only favorites", isChecked: false, number: 12}
]
}
和
_setProps() {
this.setState({
isChecked: !this.state.isChecked
});
}
然後林創造不同的組件複選框的所有元素,例如:
return (
this.props.sizes.map((size, idx) => {
return (
<Checkbox
key={"size"+idx}
label={size.label}
checked={size.isChecked}
number={size.number}
_setProps={size.props._setProps()}
/>
)
})
)
與我的CheckBox組件,在我有:
render() {
return (
<div className="Checkbox">
<form>
<input
type="checkbox"
id="check"
onClick={this.props._setProps.bind(this)}
/>
<img src={this.props.imgSrc}/>
<label htmlFor="check" id="label">{this.props.label}</label>
<label htmlFor="check" id="number">{this.props.number}</label>
</form>
</div>
)
}
和我的onClick我想改變狀態的數組中的一個元素在RootView.jsx
這可能嗎?
你想更新每個陣列的缺陷? – Codesingh
沒有,只爲這個被點擊的元素 – dobro
但缺省是在裏面的大小,評分和收藏夾 – Codesingh