# [React] React 中只有 one-way binding 但可以用 `state` 造成的 re-render 達到 two-way binding 的效果 ###### tags: `React` `前端筆記` `Udemy 課程筆記` 在學習 React 的課程中,講師示範了一個範例 `<input value={inputStateValue} onChange={onInputChangeHandler}/>`(對 `<input />` 綁定事件,並且將其值與 `state` 一起綁定),並且說這是 one-way binding,剛好看到 Q&A 有人詢問為什麼這個不是 two-way binding,就來記錄這個問題。 ## React 是透過 state 更新所造成的 re-render 模擬 two-way binding 的 ![](https://img-b.udemycdn.com/redactor/raw/q_and_a/2021-06-02_15-53-13-1d7eb5e4a5ca46037c897979a0e5ed98.gif) (參考課程 TA 在 Q&A 中的回覆) >The user types a character into the text field. That character is sent to the state via a useState() set function. This causes a re-render() of that DOM element > text field, replacing the character (with the same character) the user entered. The user can't tell their character was replaced with the same character, but, this re-render() ensures the DOM & other potential useState() invocations are kept up to date. It is good practice that; when the user causes a DOM alteration, the resulting state update is reflected in the DOM. React only has one-way binding. React simulates Two-way binding. It's the manual addition of the handler function that supplements for the missing part of the Two-way binding. This handler function contains the useState() set function. 使用者輸入觸發事件 -> 事件改變 state(`setStateFunction`)-> state 改變後觸發 component re-render -> 其 `<input value={state} />` 因為 component re-render 的緣故所以有新的 state ## 參考資料 - [In React Is there a two way data binding or only one way of data binding?](https://www.udemy.com/course/react-the-complete-guide-incl-redux/learn/lecture/25596074#questions/15039880)