Reactjs 如何使用createRef()而不是this.refs?
我在一个使用creativetim“react notification alert”的项目上工作。在他们的文档中,他们显示了一个使用警报的命令。这基本上适用于This.ref,但我知道它会贬值,所以我尝试使用createRef()替换它,如下所示:Reactjs 如何使用createRef()而不是this.refs?,reactjs,dom,undefined,ref,refs,Reactjs,Dom,Undefined,Ref,Refs,我在一个使用creativetim“react notification alert”的项目上工作。在他们的文档中,他们显示了一个使用警报的命令。这基本上适用于This.ref,但我知道它会贬值,所以我尝试使用createRef()替换它,如下所示: class App extends Component { constructor(props); this.notifRef = React.createRef(); myFunc(){ this.not
class App extends Component {
constructor(props);
this.notifRef = React.createRef();
myFunc(){
this.notifRef.current.notify.notificationAlert(options);
}
render() {
return (
<div>
<NotificationAlert ref={this.notifRef} />
<button onClick={() => this.myFunc()}>Hey</button>
</div>
);
}
}
类应用程序扩展组件{
建造师(道具);
this.notifRef=React.createRef();
myFunc(){
this.notifRef.current.notify.notificationAlert(选项);
}
render(){
返回(
这个.myFunc()}>嘿
);
}
}
但问题是控制台显示给我看
无法读取未定义的属性“notificationAlert”
我尝试了很多解决方案,在堆栈上看到了很多答案,但我很难理解它是如何工作的
谢谢你的帮助 字符串常量和createRef之间的主要区别是createRef将数据存储在
current
字段中,因为字符串常量将数据存储在这个.refs[stringConstant]中
因此,您的代码可以是:
类应用程序扩展组件{
建造师(道具){
this.notifRef=React.createRef();
}
myFunc(){
此.notifRef.current.notificationAlert(选项);
}
render(){
返回(
这个.myFunc()}>嘿
);
}
}
字符串常量和createRef之间的主要区别在于createRef将数据存储在当前
字段中,因为字符串常量将数据存储在该.refs[stringConstant]中
因此,您的代码可以是:
类应用程序扩展组件{
建造师(道具){
this.notifRef=React.createRef();
}
myFunc(){
此.notifRef.current.notificationAlert(选项);
}
render(){
返回(
这个.myFunc()}>嘿
);
}
}
试试这个:
class App extends Component {
constructor(props){
super();
this.myFunc = this.myFunc.bind( this );
}
myFunc(){
this.notifRef.current.notify.notificationAlert(options);
}
render() {
return (
<div>
<NotificationAlert ref={ e=> this.notifRef = e } />
<button onClick={ this.myFunc }>Hey</button>
</div>
);
}
}
类应用程序扩展组件{
建造师(道具){
超级();
this.myFunc=this.myFunc.bind(this);
}
myFunc(){
this.notifRef.current.notify.notificationAlert(选项);
}
render(){
返回(
this.notifRef=e}/>
嘿
);
}
}
试试这个:
class App extends Component {
constructor(props){
super();
this.myFunc = this.myFunc.bind( this );
}
myFunc(){
this.notifRef.current.notify.notificationAlert(options);
}
render() {
return (
<div>
<NotificationAlert ref={ e=> this.notifRef = e } />
<button onClick={ this.myFunc }>Hey</button>
</div>
);
}
}
类应用程序扩展组件{
建造师(道具){
超级();
this.myFunc=this.myFunc.bind(this);
}
myFunc(){
this.notifRef.current.notify.notificationAlert(选项);
}
render(){
返回(
this.notifRef=e}/>
嘿
);
}
}
很好,非常感谢你的解释,尼基塔。现在它工作正常了!我现在明白多了:)很好,非常感谢你的解释,尼基塔。现在它工作正常了!我现在更明白了:)