我是React及其流程的新手。如何将ref作为元素添加到元素?到目前为止,我的ref为null,而wordRef则为undefined。
render(){
const {
str = "Functional components cannot leverage on the performance improvements and render optimizations that come with React.",
func = function(){
const words = str.split(" ");
const els = words.map( word => {
const ref = React.createRef();
console.log('ref',ref.current); // null
return React.createElement( "wrd", {attr:"ref-"+ref}, word+" ");
});
return els;
},
wordRef = React.createRef()
} = this.props;
答案 0 :(得分:0)
您可以通过一些方法来创建参考。这是一个:
类组件:
class AutoFocusTextInput extends React.Component {
constructor(props) {
super(props);
this.textInput = React.createRef();
}
render() {
return (
<input
type="text"
ref={this.textInput} />
);
}
}
如果要将此引用作为prop传递,则需要将子组件创建为类。
功能组件:
function CustomTextInput(props) {
// textInput must be declared here so the ref can refer to it
let textInput = React.createRef();
function handleClick() {
textInput.current.focus();
}
return (
<div>
<input
type="text"
ref={textInput} />
<input
type="button"
value="Focus the text input"
onClick={handleClick}
/>
</div>
);
}
文档非常有用,您可以了解如何正确创建引用:https://reactjs.org/docs/refs-and-the-dom.html https://reactjs.org/docs/forwarding-refs.html
但是,请小心使用ref:“避免将refs用于可以声明式完成的任何事情。”