我想创建一个无状态搜索组件。单击该按钮时,我需要访问搜索字段的值。以下是可接受的方式吗?这种方法有什么缺点吗?
const Search = ({onBtnClick}) => {
const onClick = (e) => {
const query = e.target.previousSibling.value;
onBtnClick(query);
};
return(
<div>
<input type="search" />
<button onClick={onClick}>Search</button>
</div>
)
}
答案 0 :(得分:8)
在无状态组件中,您可以将ref
与function
一起使用,就像这样
const Search = ({ onBtnClick }) => {
let search;
const setNode = (node) => {
search = node;
};
const onClick = () => {
onBtnClick(search.value);
};
return (
<div>
<input type="search" ref={ setNode } />
<button onClick={ onClick }>Search</button>
</div>
);
}
function onBtnClick(value) {
console.log(value);
}
ReactDOM.render(
<Search onBtnClick={onBtnClick} />,
document.getElementById('container')
);
<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>
<div id="container"></div>
答案 1 :(得分:-1)