在这种情况下,'this.setState 放在哪里?

Where to place 'this.setState in this case?

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

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

感谢所有帮助。

您不能在应该是纯函数的 stateless 组件上调用 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>
    )
  }
}