Can you explain how this is realized through the react source code?

import React from "react"
import PureRenderMixin from "react-addons-pure-render-mixin"

import "./style.less"

class SearchInput extends React.Component {
    constructor(props, context) {
        super(props, context);
        this.shouldComponentUpdate = PureRenderMixin.shouldComponentUpdate.bind(this);
        this.state = {
            value: ""
        }
    }
    render() {
        return (
            <input
                className="search-input" 
                type="text" 
                placeholder="" 
                onChange={this.ChangeHandle.bind(this)}
                onKeyUp={this.KeyUpHandle.bind(this)}
                value={this.state.value}/>
        )
    }
    componentDidMount() {
        // 
        this.setState({
            value: this.props.value || ""
        })
    }
    ChangeHandle(e) {
        // 
        this.setState({
            value: e.target.value
        })
    }
    KeyUpHandle(e) {
        //  enter 
        if (e.keyCode !== 13) {
            return
        }
        this.props.enterHandle(e.target.value)
    }
}

export default SearchInput

onChange= {this.ChangeHandle.bind (this)}
value= {this.state.value}
thought it was an endless cycle at first. Re-assign the value to input when value is set. OnChange is triggered after the assignment. This is an endless cycle. But there is no endless cycle. And React officials also recommend this way of writing-- how does the source code handle it?

Mar.07,2021

Why do you think there will be an endless cycle?


re-assignment does not trigger the onChange event, which is an event in the dom layer, and like onKeyUp, setState simply informs the view internally that it is time to re-render.


there will be no endless loop. SetState will reassign the field value and will not trigger the bound onChange event actively. If the state changes, the view will be rendered again, and will not trigger the bound event


in a sentence: react is an one-way data binding.


react-DOM 's onChange is quite different from DOM's onchange , it is a veritable "change". From the point of view of the source code, Mainly listening to change , input and click to listen for changes in various components. None of these events are triggered by setting value through DOM api. In fact, DOM provides dispatchEvent to trigger events manually.


onChange will only be triggered when the DOM change event occurs in the input element, and no event will occur in the reassignment process, so it will not cycle

.
Menu