如何将数据从props中的一个变量传递到React应用程序中的另一个变量?

时间:2018-10-14 09:03:30

标签: reactjs closures dataflow

class StarRating extends Component {
  constructor (props) {
    super(props)
}

 log = (selected) => {
  console.log(selected)
}

  render() {
        return <div>
          <Star
          selected = {true}
          doClick={() => this.log(this.selected)}
          />
          <Star />
          <Star/>
          <Star/>
          <Star/>
          </div>
        }
}

我需要传递“ selected”(在我的情况下为“ true”)才能登录,但是它写为“ undefined”,我应该更改什么?

这是Star组件。

const Star =  ({selected, doClick=f=>f}) =>
<div className = {(selected) ? "star selected" : "star"} onClick={doClick}></div>

Star.propTypes = {
selected: PropTypes.bool,
doClick: PropTypes.func
}
export default Star

1 个答案:

答案 0 :(得分:1)

您需要像下面那样构造StarRating组件

class StarRating extends Component {
    constructor (props) {
      super(props);
      this.state = {
        selected: false
      }
  }

   log = () => {
    this.setState({
        selected: true
    });
  }

    render() {
          return <div>
            <Star
            selected = {this.state.selected}
            doClick={this.log}
            />
            <Star />
            <Star/>
            <Star/>
            <Star/>
            </div>
          }
  }

const Star =  ({selected, doClick}) => <div className = {(selected) ? "star selected" : "star"} onClick={doClick}></div>

Star.propTypes = {
  selected: PropTypes.bool,
  doClick: PropTypes.func
}
export default Star;