【发布时间】:2020-06-10 21:52:34
【问题描述】:
在this question 的帮助下,我已将 React 类组件转换为函数组件。
除此按钮外,一切正常:
{/*
Show only if user has typed in search.
To reset the input field, we pass an
empty value to the filterUpdate method
*/}
{hasSearch && <button onClick={filterUpdate}>Clear Search</button>}
当我点击它时,我会在搜索框中看到[object Object]。我也试过了:
{hasSearch && <button onClick={filterUpdate("")}>Clear Search</button>}
但这会使搜索功能停止工作。 这是旧的(类组件)代码(正在工作)。
{hasSearch && (
<button onClick={this.filterUpdate.bind(this, "")}>
Clear Search
</button>
)}
所有代码都在另一个问题中。不过,这提供了上下文。
// update filterText in state when user types
const filterUpdate = (value) => {
setfilterText(value);
};
/* ###################### */
/* ##### Search bar ##### */
/* ###################### */
// need a component class here
// since we are using `refs`
class Search extends Component {
render() {
const { filterVal, filterUpdate } = this.props;
return (
<form>
<input
type="text"
ref="filterInput"
placeholder="Type to filter.."
// binding the input value to state
value={filterVal}
onChange={() => {
filterUpdate(this.refs.filterInput.value);
}}
/>
</form>
);
}
}
【问题讨论】:
标签: javascript reactjs