reactjs - reactjs - 如何綁定選擇?


import React, { useState } from"react";


import"./styles.css";



export default function App() {


 const [optionValue, setOptionValue] = useState([1, 2, 3]);



 const onHandleOption = () => {


 return optionValue.map((i, idx) => {


 return <option id={idx}>{i}</option>;


 });


 };



 return (


 <div className="App">


 <p>Main select</p>


 <select>{onHandleOption()}</select>



 <p>Attached select</p>


 <select>{onHandleOption()}</select>


 </div>


 );


}

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>


<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

时间: 作者:

可以為select元素設置值:<select value={selectValue} />

然後,在第一個select元素的onChange中,要設置選定項的狀態,並確保它是第二個select元素的值。

比如:


const [selectedOption, setSelectedOption] = useState(someOption);



<select onChange={set option here} />


<select value={selectedOption} />




React表單文檔參考:https://reactjs.org/docs/forms.html

作者:
...