React 从其 children 中获取 parent 道具的正确方法是什么

React what's the right way to get a parent props from its children

请耐心等待,我是 React 的新手。

在这段代码中(它不起作用)我想要,

在CommentForm中,获取url props的值

来自评论框。

var CommentBox = React.createClass({
  render: function() {
    return (
      <div className="commentBox">
        <h1>Comments</h1>
        <CommentList />
        <CommentForm />
      </div>
    );
  }
});

var CommentList = React.createClass({
  render: function() {
    return (
      <div className="commentList">
        Hello, world! I am a CommentList.
      </div>
    );
  }
});

var CommentForm = React.createClass({
  render: function() {
    return (
      <div className="commentForm">
        Hello,  my test url {this.props.url} !.
      </div>
    );
  }
});

React.render(
  <CommentBox url="api/comments" />,
    document.getElementById('content')
);

正确的方法是什么?

以及为什么无法直接从 parent 到 children 使用道具?

您需要明确地将道具从 parent 传递到 child。更改 CommentBoxrender 函数将解决问题:

var CommentBox = React.createClass({
  render: function() {
    return (
      <div className="commentBox">
        <h1>Comments</h1>
        <CommentList />
        //The next line is where you can pass the URL to the CommentForm
        <CommentForm url={this.props.url}/>
      </div>
    );
  }
});

根据您的示例改编的工作 jsfiddle:http://jsfiddle.net/kb3gN/10352/

文档说 "For parent-child communication, simply pass props." 请参阅 http://facebook.github.io/react/tips/communicate-between-components.html

作为显式传递 props 的替代方法,React 未记录的 context 功能更接近您正在寻找的功能: https://www.tildedave.com/2014/11/15/introduction-to-contexts-in-react-js.html 并且在 1.0 https://facebook.github.io/react/blog/2014/03/28/the-road-to-1.0.html#context.

的路线图上

也就是说,传递道具是正常模式。