编辑:您现在可以使用React Hooks。 请参阅Ante Gulin的答案。
您无法访问做出反应等的方法(例如
componentDidMount,
componentWillReceiveProps在无状态组件等)在内
refs。查看有关GH的完整讨论。
无状态的想法是没有为其创建一个实例(状态)。因此,您无法附加
ref,因为没有将引用附加到的状态。
最好的选择是在组件发生更改时传递回调,然后将该文本分配给父对象的状态。
或者,您可以完全放弃无状态组件,而使用普通的类组件。
从文档…
您不能在功能组件上使用ref属性,因为它们没有实例。但是,您可以在功能组件的render函数内使用ref属性。
function CustomTextInput(props) { // textInput must be declared here so the ref callback can refer to it let textInput = null; function handleClick() { textInput.focus(); } return ( <div> <input type="text" ref={(input) => { textInput = input; }} /> <input type="button" value="Focus the text input" onClick={handleClick} /> </div> ); }


