开发者问题收集

react ref 值为空

2018-11-22
2604

我有一个带有不受控制的输入元素的反应组件,如下所示:

class TestComponent {

onAddTypeClicked = el => {
    console.log(el);
    console.log(el.value);
};


render() {
    return (
        <div>
            <input
                name="asset_types"
                ref={el => this.assetTypesAdd = el}
            />
            <button
                type="button"
                onClick={e => this.onAddTypeClicked(this.assetTypesAdd)}
            />   
        </div>
    );
}

现在,当我在输入字段中输入一些值并单击按钮时,输入会正确打印,但其值为空。但如果我使用 document.getElementById 方法,它会正常工作。有人能指出我是否做错了什么吗?

1个回答

我相信您的代码运行正常,并且 this.assetTypesAdd.value 中 accessible 的值与其打印的值相同。我不确定您在哪里获得输入的空值。

// Example class component
class MyComponent extends React.Component {

  onAddTypeClicked = el => {
      console.log(el.value);
      this.forceUpdate();
  };

  render() {
    return (
        <div>
            <input
                name="asset_types"
                ref={el => this.assetTypesAdd = el}
            />
            <button
                type="button"
                onClick={e => this.onAddTypeClicked(this.assetTypesAdd)}
            >
                Click me
            </button>
            {this.assetTypesAdd && 
                <div>Value of input: {this.assetTypesAdd.value}</div>}
            
        </div>
    );
  }
}

// Render it
ReactDOM.render(
  <MyComponent/>,
  document.getElementById("react")
);
button {
    width: 100px;
    height: 20px;
    display: block;
    margin: 10px 0;
}
<div id="react"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
Shawn Andrews
2018-11-22