重新渲染时如何更新组件状态

时间:2018-12-07 10:15:54

标签: reactjs

嗨,我正在尝试在渲染过程中更改组件的状态。国家应根据作为道具传递给它的列表来更改类名。我已经尝试过了,但是似乎没有用。我可以传递道具,但不能更改状态。

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 };
})();

1 个答案:

答案 0 :(得分:0)

我在SquareSquareList组件中进行了以下更改。您需要将道具道具传递到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 };
})();
相关问题