react 使用 ref 报错 ,[eslint] Using string literals in ref attributes is deprecated. (react/no-string-refs)

时间:2023-03-08 16:05:27

react 项目中给指定元素加事件,使用到 react 的 ref 属性,Eslink 报错 [eslint] Using string literals in ref attributes is deprecated. (react/no-string-refs)

常用方法:(会报错)


var Hello = createReactClass({
componentDidMount: function() {
var component = this.refs.hello;
// ...do something with component
},
render: function() {
return <div ref="hello">Hello, world.</div>;
}
});

正确方法:

 var Hello = createReactClass({
componentDidMount: function() {
var component = this.hello;
// ...do something with component
},
render() {
return <div ref={(c) => { this.hello = c; }}>Hello, world.</div>;
}
});