我有一个带有不受控制的输入元素的react组件,如下所示:
function openEvt(evt, evtName) {
var i, tabcontent, tablinks;
tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = "none";
}
tablinks = document.getElementsByClassName("tablinks");
for (i = 0; i < tablinks.length; i++) {
tablinks[i].className = tablinks[i].className.replace(" active", "");
}
document.getElementById(evtName).style.display = "block";
evt.currentTarget.className += " active";
}
现在,当我在输入字段中键入一些值并单击按钮时,输入将正确打印,但其值为空。如果我使用document.getElementById方法,则效果很好。有人可以指出我做错了什么吗?
答案 0 :(得分: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>