gpt4 book ai didi

javascript - 使用 this.refs 的弃用警告

转载 作者:IT王子 更新时间:2023-10-29 03:13:47 28 4
gpt4 key购买 nike

我有一个 React 组件,我想在点击时切换一个 css 类。

所以我有这个:

export class myComponent extends React.Component {
constructor() {
super();
this.state = { clicked: false };
this.handleClick = this.handleClick.bind(this);
}

render() {
return (
<div>
<div onClick={this.clicked}><span ref="btn" className="glyphicon">&nbsp;</span></div>
</div>
);
}

handleClick() {
this.refs.btn.classList.toggle('active');
}

componentDidMount() {
this.refs.btn.addEventListener('click', this.handleClick);
this.setState({
clicked: this.state.clicked = true,
});
}

componentWillUnmount() {
this.refs.btn.removeEventListener('click', this.handleClick);
this.setState({
clicked: this.state.clicked = false,
});
}
}

这个问题是 ESLint 一直告诉我“this.refs”已贬值。

我该怎么办?我该如何修复它,使其不使用折旧代码?

最佳答案

您所指的 Lint 规则称为 no-string-refs并警告你:

"Using string literals in ref attributes is deprecated (react/no-string-refs)"

您收到此警告是因为已经实现了使用 refs 的弃用方式(通过使用字符串)。根据您的 React 版本,您可以:

React 16.3 及更高版本

constructor() {
super();
this.btnRef= React.createRef();
this.state = { clicked: false };
this.handleClick = this.handleClick.bind(this);
}

render() {
return (
<div>
<div onClick={this.addVote}><span ref={this.btnRef} className="glyphicon">&nbsp;</span></div>
</div>
);
}

React 16.2 及更早版本

constructor() {
super();
this.btnRef; //not necessary to declare the variable here, but I like to make it more visible.
this.state = { clicked: false };
this.handleClick = this.handleClick.bind(this);
}

render() {
return (
<div>
<div onClick={this.addVote}><span ref={(el) => this.btnRef = el} className="glyphicon">&nbsp;</span></div>
</div>
);
}

为了更好的可读性,你还可以这样做:

render() {
let myRef = (el) => this.btnRef = el;
return (
<div>
<div onClick={this.addVote}><span ref={myRef} className="glyphicon">&nbsp;</span></div>
</div>
);
}

看看官方文档在 Refs and the DOM 上是怎么说的, 和 this section特别是:

Legacy API: String Refs

If you worked with React before, you might be familiar with an older API where the ref attribute is a string, like "textInput", and the DOM node is accessed as this.refs.textInput. We advise against it because string refs have some issues, are considered legacy, and are likely to be removed in one of the future releases. If you're currently using this.refs.textInput to access refs, we recommend the callback pattern instead.

关于javascript - 使用 this.refs 的弃用警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43873511/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com