反应|解除状态后如何控制子组件

时间:2019-01-22 00:49:25

标签: javascript reactjs ecmascript-6

我如何解除状态,仍然能够让父组件告诉子组件的元素是否应该可见?

建议我让我的<List />为每个<li />处理自己的状态

class HeroList extends Component {
  state = {
    show: false
  };

  handleShow = () => {
    this.setState({ show: true });
  };

  getColor = () => {
    if (this.state.show) {
      if (this.props.isCorrect) {
        return "green";
      } else {
        return "red";
      }
    }
    return "";
  };

  render() {
    console.log('rendered list again')
    const { name, color } = this.props;
    const { show } = this.state;
    return (
      <li onClick={this.handleShow} className={this.getColor()}>
        {name}
        <span className={show ? "show" : "hide"}>{color}</span>
      </li>
    );
  }
}

但是,当我从父组件调用我的shuffle方法时,即使<List/>组件经历了新渲染,其状态也不会回到初始状态:即show:false仍为show:true

export default class Heroes extends Component {
  state = {
    heroes: [
      { name: "Aquaman", color: "orange", id: 1 },
      { name: "Batman", color: "black", id: 2 },
      { name: "Green Lantern", color: "green", id: 3 },
      { name: "SuperMan", color: "blue", id: 4 },
      { name: "SpiderMan", color: "red", id: 5 }
    ]
  };

  /****** SHUFFLE METHOD ******/
  handleShuffle = () => {
    this.setState({
      heroes: [...this.state.heroes.sort(() => Math.random() - 0.5)]
    });
  };

  render() {
    const { heroes } = this.state;
    const correctIndex = Math.floor(Math.random() * (heroes.length - 1));
    const correctHero = heroes[correctIndex];

    const hero = heroes.map(hero => (
      <HeroList
        key={hero.id}
        name={hero.name}
        color={hero.color}
        isCorrect={correctHero.color === hero.color}
      />
    ));

    return (
      <>
        <h6>React Controlled Components</h6>
        <Question key={correctHero.id} color={correctHero.color} />
        <button onClick={this.handleShuffle}>shuffle heroes</button>
        <ul>{hero}</ul>
      </>
    );
  }
}

// Question
const Question = ({ color }) => <h2>What Hero wears {color}</h2>;

然后建议我将状态提升为上级组件,并将状态作为道具传递给下级,但是随后我遇到了一个阻塞器,当show: true对应一个<li />时,所有他们是在第一个onClick事件中出现的。

问题:我如何提升状态,但仍然控制每个<li/>来分别更改onClick

您可以在此处看到问题所在,请随时分叉=> code sandbox

1 个答案:

答案 0 :(得分:2)

您需要维护父组件状态下的显示状态列表,并根据单击的英雄项进行操作。

解决方案

Edit react-controlled-components