Reproducing this interaction in React requires knowledge of a few principles:
- Event handlers are attached to an element as a property. If using JSX, be careful not to enclose the handler in quotes!
< input onclick={this.submitSearch} type="button" value="Search" />
- The "this" context pointing to the React component is not available in the event handler. That means that if the value in the text box is bound to a member of the component state, this value would not be accessible in the handler. There are two approaches to correcting this - either add the "bind(this)" call to the end of the handler invocation
< input onclick={this.submitSearch.bind(this)} type="button" value="Search" />
or define the handler as an arrow functionsubmitSearch = ( e ) => { … }
- Bind the text box default value to an initial value. Do not bind the value property, as doing so causes the box to behave as read only in the form. Also need to add an onchange handler for the text box, bound to a function that updates the appropriate member of the state object with the value from the control (e.target.value)
- Add the shouldComponentUpdate() lifecycle function to the component, ensuring that the change of text value in the state member does not trigger the update (unless you want the search to occur on every key stroke)
- Setting the state in React (using Typescript in VS Code) requires all members of the state object to be set each time
No comments:
Post a Comment