javascript 反应:为什么`this.props.children`未定义?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20898401/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 19:34:34  来源:igfitidea点击:

React: Why is `this.props.children` undefined?

javascriptreactjs

提问by Matt Harrison

I'm building an electronic resistance calculator with ReactJS. I have a composed component declared as so:

我正在用 ReactJS 构建一个电子电阻计算器。我有一个这样声明的组合组件:

var ResistanceCalculator = React.createClass({
    getInitialState: function() {
        return {bands: [0,0,0,0,0]}
    },
    componentDidMount: function() {
        console.log(this.props.children); // => undefined
    },
    render: function() {
        return (
            <div>
                <OhmageIndicator bands={this.state.bands} />
                <SVGResistor bands={this.state.bands} />
                <BandSelector band={1} />
                <BandSelector band={2} />
                <BandSelector band={3} />
                <BandSelector band={4} />
                <BandSelector band={5} />
            </div>
         );
    }
});

BandSelector renders <select>elements and when one changes I want to update ResistanceCalculator's state. So my thinking was that I need to bind an event listener to ResistanceCalculatorchildren. However this.props.childrenseems to be empty. Why is this?

BandSelector 呈现<select>元素,当一个元素发生变化时,我想更新ResistanceCalculator的状态。所以我的想法是我需要给ResistanceCalculator孩子绑定一个事件监听器。不过this.props.children好像是空的。为什么是这样?

回答by chenglou

The rule of thumb is: everything that's in this.propsis passed down to you from the parent. So you're using this.props.childrenthe wrong way. If I had something like this:

经验法则是:里面的所有东西都是this.props从父母那里传给你的。所以你用this.props.children错了方法。如果我有这样的事情:

<Todos><div /><div /></Todos>

then, for the Todoscomponent, this.props.childrenwould be the array of divs.

然后,对于Todos组件,this.props.children将是divs.

What you want here are simple callbacks (working example):

你在这里想要的是简单的回调(工作示例):

/** @jsx React.DOM */
var ResistanceCalculator = React.createClass({
  getInitialState: function() {
      return {bands: [0,0,0,0,0]};
  },

  handleBandSelectionChange: function(bandIndex, newValue) {
    // for the sake of immutability, clone the array here
    var bands = this.state.bands.slice(0);
    bands[bandIndex] = newValue;
    console.log(bandIndex, newValue); // yep, seems to work
    this.setState({bands: bands});
  },

  render: function() {
    return (
      <div>
        <OhmageIndicator bands={this.state.bands} />
        {
          this.state.bands.map(function(value, i) {
            return (
              <BandSelector band={i} onChange={this.handleBandSelectionChange}/>
            );
          }, this)
        }
      </div>
    );
  }
});

var BandSelector = React.createClass({
  handleChange: function(e) {
    if (this.props.onChange)
      this.props.onChange(this.props.band, e.target.value);
  },

  render: function() {
    return (
      <select onChange={this.handleChange}>
        <option value="1">1</option>
        <option value="2">2</option>
      </select>
    );
  }
});

I listen to the regular onChangeevent from select, then in the handler I call my parent's handler (handleBandSelectionChange). Note that, for the parent (ResistanceCalculator), the event doesn't have to be onChange; it could be any name, as long as the child calls it. It's just nicer to name it onChange.

onChange从 select 中收听常规事件,然后在处理程序中调用我父母的处理程序 ( handleBandSelectionChange)。请注意,对于父级 ( ResistanceCalculator),事件不必是onChange; 它可以是任何名字,只要孩子叫它。给它起个名字更好onChange

As a side note, this.props.childrenis used for wrapper components who want to transparently render their content while doing some work themselves.

作为旁注,this.props.children用于希望在自己做一些工作的同时透明地呈现其内容的包装器组件。