reactJS道具和refs有什么区别?

时间:2015-08-02 08:31:35

标签: javascript reactjs

我对ReactJS中的propsrefs感到困惑。任何人都可以通过恰当的例子向我解释它们之间的区别。 提前谢谢。

4 个答案:

答案 0 :(得分:5)

道具用于传递应该是静态的参数(与状态相反)。例如,您可以将大小或名称从upperView传递给lowerView(嵌套视图);

有关道具的有趣部分:https://facebook.github.io/react/docs/transferring-props.html

refs用于访问真正的DOM而不是反应的虚拟DOM。当您需要访问真正的DOM时,需要它。

这部分很有趣:https://facebook.github.io/react/docs/more-about-refs.html

 this.setState({userInput: ''}, function() {
        // This code executes after the component is re-rendered
        React.findDOMNode(this.refs.theInput).focus();   // Boom! Focused!
      });

上面的示例向您展示了在更新状态时如何正确访问DOM元素

希望它有所帮助。

答案 1 :(得分:1)

For sure there are differences between, one mostly use for selecting the DOM, one for getting data as a property, I create the image below and explain few major differences:

enter image description here

Also this the sample of grandparent, parent and child components which using ref and props to pass data, it's a good example to understand when and how they get used, please pay attention how ref helping to get in deeper component by referencing to the element:

function Child(props) {
  return (
    <div>
      <input ref={props.inputRef} />
    </div>
  );
}

function Parent(props) {
  return (
    <div>
      My input: <Child inputRef={props.inputRef} />
    </div>
  );
}

class Grandparent extends React.Component {
  render() {
    return (
      <Parent
        inputRef={el => this.inputElement = el}
      />
    );
  }
}

答案 2 :(得分:0)

这是两件不同的事情。

道具:使用它们将任何参数传递给您的组件。

参考:参考文献的快捷方式。这些是对DOM元素的引用。如果由于某种原因需要访问原始DOM元素,请使用它们。例如,通过.addEventListener()函数添加自定义事件处理程序。

答案 3 :(得分:0)

除了弗朗索瓦·理查德的上述答案之外,你可能还想读: https://github.com/uberVU/react-guide/blob/master/props-vs-state.md

因为在州和道具之间更常混淆。 祝你好运