嗨,我正在尝试在渲染过程中更改组件的状态。国家应根据作为道具传递给它的列表来更改类名。我已经尝试过了,但是似乎没有用。我可以传递道具,但不能更改状态。
class Square extends React.Component {
constructor(props) {
super(props);
this.state = {alive: true};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState(state => ({
alive: !state.alive
}));
};
render() {
return <div className = { this.state.alive ? "square--green" : "square--grey" } onClick = { this.handleClick } />;
};
}
function SquareList(props) {
const oxGrid = props.oxGrid;
const listItems = [];
oxGrid.forEach((item, i) => {
if(item === 'O'){
listItems.push(<Square key= {i}/>)
}
else {
listItems.push(<Square key = {i} />)
}
});
return listItems;
};
let printer = (function () {
let print = function (oXGrid) {
return ReactDOM.render(<SquareList oxGrid ={oXGrid} />, grid);
};
return { print: print };
})();
答案 0 :(得分:0)
我在Square
和SquareList
组件中进行了以下更改。您需要将道具道具传递到Square
组件。
class Square extends React.PureComponent {
constructor(props) {
super(props);
const isALive = this.props.item === 'O';
this.state = {
alive: isALive
};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState(state => ({
alive: !state.alive
}));
};
componentWillReceiveProps(nextProps) {
if(this.props.item !== nextProps.item) {
this.setState({
alive: nextProps.item === '0'
});
}
}
render() {
return <div className = { this.state.alive ? "square--green" : "square--grey" } onClick = { this.handleClick } />;
};
}
function SquareList(props) {
const oxGrid = props.oxGrid;
const listItems = oxGrid.map((item, i) => {
return(
<Square item={item} key= {i}/>
)
});
return listItems;
};
let printer = (function () {
let print = function (oXGrid) {
return ReactDOM.render(<SquareList oxGrid ={oXGrid} />, grid);
};
return { print: print };
})();