gpt4 book ai didi

reactjs - 为什么 this.refs 未定义?

转载 作者:行者123 更新时间:2023-12-02 15:29:56 24 4
gpt4 key购买 nike

为什么下面的代码中 this.refs 未定义?

class NewItem extends React.Component {
handleClick() {
console.log(this.refs) //prints out undefined
const name = this.refs.name.value;
const description = this.refs.description.value;
$.ajax({
url: 'api/v1/items',
type: 'POST',
data: {
item: {
name: name,
description: description
}
},
success: (item) => {
this.props.handleSubmit(item);
}
});
}

render() {
return (
<div>
<input ref='name' placeholder='Enter the name of the item' />
<input ref='description' placeholder='Enter the description of the item' />
<button onClick={this.handleClick}>Submit</button>
</div>
)
}
}

最佳答案

当用作函数时,该方法未绑定(bind)到 this:

<button onClick={this.handleClick.bind(this)}>Submit</button>

<button onClick={event => this.handleClick(event)}>Submit</button>

或将其绑定(bind)在构造函数中:

constructor(props, context) {
super(props, context);

this.handleClick = this.handleClick.bind(this);
}

关于reactjs - 为什么 this.refs 未定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43909639/

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