在这种情况下放置'this.setState?

时间:2017-07-12 18:22:50

标签: reactjs onclick state setstate

我正在尝试创建一个页面,您可以单击缩略图,然后使用状态显示要放大的版本。让状态正常工作,但是当我尝试在缩略图上的Cannot read property 'setState' of undefined中设置它时,我收到错误消息onClick。我可以理解为什么它不能像这样真正起作用,但很难理解如何安排它按照我打算的方式工作。这是有问题的代码:

const WorkThumb = ({work}) => (
  <Col xs={3} md={4}>
    <WorkImage src={work.metadata.image.imgix_url} onClick={this.setState({selected: work._id})} />
  </Col>
)

export default class ArtContent extends React.Component {

  constructor(props) {
    super(props);
    this.state = {selected: props.works[0]["_id"]};
  }

  render () {
    return (
      <Row>
        <Col xs={6}>
          <Row between="xs" center="xs" middle="xs">
            {this.props.works.map((work) => (
              <WorkThumb key={work._id} work={work} />
            ))}
          </Row>
        </Col>
        <Col xs={6}>
          <Selected src={this.props.works.filter((work) => (work["_id"] == this.state.selected))[0].metadata.image.imgix_url} />
        </Col>
      </Row>
    )
  }
}

所有帮助表示赞赏。

1 个答案:

答案 0 :(得分:1)

你不能在应该是纯函数的无状态组件上调用setState(即仅依赖于它的参数:没有this上下文,没有状态,相同的输入 - 相同的输出)。但是你可以从有状态的父母传递回调

const WorkThumb = ({work, onSelect}) => (
  <Col xs={3} md={4}>
    <WorkImage src={work.metadata.image.imgix_url} onClick={() => onSelect(work)} />
  </Col>
)

export default class ArtContent extends React.Component {

  constructor(props) {
    super(props);
    this.state = {selected: props.works[0]["_id"]};
    this.selectWork = this.selectWork.bind(this)
  }

  selectWork(work) {
    this.setState(...)
  } 

  render () {
    return (
      <Row>
        <Col xs={6}>
          <Row between="xs" center="xs" middle="xs">
            {this.props.works.map((work) => (
              <WorkThumb key={work._id} work={work} onSelect={this.selectWork} />
            ))}
          </Row>
        </Col>
        <Col xs={6}>
          <Selected src={this.props.works.filter((work) => (work["_id"] == this.state.selected))[0].metadata.image.imgix_url} />
        </Col>
      </Row>
    )
  }
}