ReactJ의 라디오 버튼을 사용하는 방법
리액트J는 처음이라서 안 들리면 미안해요.수신한 데이터에 따라 여러 테이블 행을 생성하는 컴포넌트가 있습니다.
컬럼 내의 각 셀에는 무선 체크박스가 있습니다.에, 는 1개의 「1」을 할 수 .site_name
1개의 ★★★★★★★★★★★★★★.address
기존 행에서 선택합니다.선택은 바닥글에 표시되어야 한다.그리고 그것이 내가 갇혀있는 곳이다.
var SearchResult = React.createClass({
render: function () {
var resultRows = this.props.data.map(function (result) {
return (
<tbody>
<tr>
<td>
<input type="radio" name="site_name" value={result.SITE_NAME}>
{result.SITE_NAME}
</input>
</td>
<td>
<input type="radio" name="address" value={result.ADDRESS}>
{result.ADDRESS}
</input>
</td>
</tr>
</tbody>
);
});
return (
<table className="table">
<thead>
<tr>
<th>Name</th>
<th>Address</th>
</tr>
</thead>
{resultRows}
<tfoot>
<tr>
<td>chosen site name ???? </td>
<td>chosen address ????? </td>
</tr>
</tfoot>
</table>
);
},
});
에서는 jQuery를 할 수.$("input[name=site_name]:checked").val()
하나의 라디오 체크박스를 선택하여 첫 번째 바닥글 셀에 삽입합니다.
하지만 분명히 리액트 방법이 있을 거야, 내가 완전히 놓치고 있는 거지?대단히 고맙습니다
은 모두 '변경'을 해야 합니다.state
★★★★★★★★★★★★★★★★★」props
(문서 참조).
하고, 그 후 '이벤트'를 합니다.state
그러면 바닥글에 렌더가 표시됩니다.
var SearchResult = React.createClass({
getInitialState: function () {
return {
site: '',
address: '',
};
},
onSiteChanged: function (e) {
this.setState({
site: e.currentTarget.value,
});
},
onAddressChanged: function (e) {
this.setState({
address: e.currentTarget.value,
});
},
render: function () {
var resultRows = this.props.data.map(function (result) {
return (
<tbody>
<tr>
<td>
<input
type="radio"
name="site_name"
value={result.SITE_NAME}
checked={this.state.site === result.SITE_NAME}
onChange={this.onSiteChanged}
/>
{result.SITE_NAME}
</td>
<td>
<input
type="radio"
name="address"
value={result.ADDRESS}
checked={this.state.address === result.ADDRESS}
onChange={this.onAddressChanged}
/>
{result.ADDRESS}
</td>
</tr>
</tbody>
);
}, this);
return (
<table className="table">
<thead>
<tr>
<th>Name</th>
<th>Address</th>
</tr>
</thead>
{resultRows}
<tfoot>
<tr>
<td>chosen site name {this.state.site} </td>
<td>chosen address {this.state.address} </td>
</tr>
</tfoot>
</table>
);
},
});
react js에서 라디오 버튼을 구현하는 가장 간단한 방법은 다음과 같습니다.
class App extends React.Component {
setGender(event) {
console.log(event.target.value);
}
render() {
return (
<div onChange={this.setGender.bind(this)}>
<input type="radio" value="MALE" name="gender"/> Male
<input type="radio" value="FEMALE" name="gender"/> Female
</div>
)
}
}
ReactDOM.render(<App/>, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
편집필
바인딩 대신 화살표 기능을 사용할 수 있습니다.위의 코드를 다음과 같이 바꿉니다.
<div onChange={event => this.setGender(event)}>
는, 「」를 합니다.defaultChecked
이렇게.
<input type="radio" value="MALE" defaultChecked name="gender"/> Male
React Docs에 따르면:
여러 입력 처리여러 개의 제어된 입력 요소를 처리해야 할 경우 각 요소에 이름 속성을 추가하여 핸들러 함수가 event.target.name 값을 기반으로 수행할 작업을 선택할 수 있습니다.
예를 들어 다음과 같습니다.
class App extends React.Component {
constructor(props) {
super(props);
this.state = {};
}
handleChange = e => {
const { name, value } = e.target;
this.setState({
[name]: value
});
};
render() {
return (
<div className="radio-buttons">
Windows
<input
id="windows"
value="windows"
name="platform"
type="radio"
onChange={this.handleChange}
/>
Mac
<input
id="mac"
value="mac"
name="platform"
type="radio"
onChange={this.handleChange}
/>
Linux
<input
id="linux"
value="linux"
name="platform"
type="radio"
onChange={this.handleChange}
/>
</div>
);
}
}
링크 예: https://codesandbox.io/s/6l6v9p0qkr
되지 않았기 때문에, 「」는 선택되지 .this.state
this.state
는 입력 이름과 해당 값이 포함된 새 속성을 가져옵니다.그런 다음 사용자가 다음과 같은 라디오 버튼을 선택했는지 여부를 쉽게 확인할 수 있습니다.
const isSelected = this.state.platform ? true : false;
편집:
React 버전 16.7-alpha에서는 다음과 같은 제안이 있습니다.hooks
더 할 수 있을 거예요.
아래 예에서는 기능 컴포넌트에 무선 버튼의 2개의 그룹이 있습니다.그래도 입력은 제어되고 있습니다.
function App() {
const [platformValue, plaftormInputProps] = useRadioButtons("platform");
const [genderValue, genderInputProps] = useRadioButtons("gender");
return (
<div>
<form>
<fieldset>
Windows
<input
value="windows"
checked={platformValue === "windows"}
{...plaftormInputProps}
/>
Mac
<input
value="mac"
checked={platformValue === "mac"}
{...plaftormInputProps}
/>
Linux
<input
value="linux"
checked={platformValue === "linux"}
{...plaftormInputProps}
/>
</fieldset>
<fieldset>
Male
<input
value="male"
checked={genderValue === "male"}
{...genderInputProps}
/>
Female
<input
value="female"
checked={genderValue === "female"}
{...genderInputProps}
/>
</fieldset>
</form>
</div>
);
}
function useRadioButtons(name) {
const [value, setState] = useState(null);
const handleChange = e => {
setState(e.target.value);
};
const inputProps = {
name,
type: "radio",
onChange: handleChange
};
return [value, inputProps];
}
작업 예: https://codesandbox.io/s/6l6v9p0qkr
라디오 컴포넌트를 멍청한 컴포넌트로 만들어 부모로부터 소품을 전달합니다.
import React from "react";
const Radiocomponent = ({ value, setGender }) => (
<div onChange={setGender.bind(this)}>
<input type="radio" value="MALE" name="gender" defaultChecked={value ==="MALE"} /> Male
<input type="radio" value="FEMALE" name="gender" defaultChecked={value ==="FEMALE"}/> Female
</div>
);
export default Radiocomponent;
덤 컴포넌트(순수한 기능)이기 때문에 테스트도 간단합니다.
여기서 한 가지 아이디어가 있습니다.Respect에서의 무선 입력에 관해서는, 통상, 앞의 회답에서 말한 것과 다른 방법으로 모든 것을 렌더링합니다.
이렇게 하면 많은 옵션버튼을 렌더링할 필요가 있는 사용자에게 도움이 되는 경우:
import React from "react"
import ReactDOM from "react-dom"
// This Component should obviously be a class if you want it to work ;)
const RadioInputs = (props) => {
/*
[[Label, associated value], ...]
*/
const inputs = [["Male", "M"], ["Female", "F"], ["Other", "O"]]
return (
<div>
{
inputs.map(([text, value], i) => (
<div key={ i }>
<input type="radio"
checked={ this.state.gender === value }
onChange={ /* You'll need an event function here */ }
value={ value } />
{ text }
</div>
))
}
</div>
)
}
ReactDOM.render(
<RadioInputs />,
document.getElementById("root")
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
import React, { Component } from "react";
class RadionButtons extends Component {
constructor(props) {
super(props);
this.state = {
// gender : "" , // use this one if you don't wanna any default value for gender
gender: "male" // we are using this state to store the value of the radio button and also use to display the active radio button
};
this.handleRadioChange = this.handleRadioChange.bind(this); // we require access to the state of component so we have to bind our function
}
// this function is called whenever you change the radion button
handleRadioChange(event) {
// set the new value of checked radion button to state using setState function which is async funtion
this.setState({
gender: event.target.value
});
}
render() {
return (
<div>
<div check>
<input
type="radio"
value="male" // this is te value which will be picked up after radio button change
checked={this.state.gender === "male"} // when this is true it show the male radio button in checked
onChange={this.handleRadioChange} // whenever it changes from checked to uncheck or via-versa it goes to the handleRadioChange function
/>
<span
style={{ marginLeft: "5px" }} // inline style in reactjs
>Male</span>
</div>
<div check>
<input
type="radio"
value="female"
checked={this.state.gender === "female"}
onChange={this.handleRadioChange}
/>
<span style={{ marginLeft: "5px" }}>Female</span>
</div>
</div>
);
}
}
export default RadionButtons;
여기 제가 사용한 것이 있습니다.이게 도움이 됐으면 좋겠다.
먼저 변수를 정의합니다.
const [variableName, setVariableName] = useState("");
그러면 실제 라디오 버튼이 필요합니다.
<input
type="radio"
name="variableName"
value="variableToCheck"
onChange={(e) =>
setVariableName("variableToCheck")
}
checked={variableName === "variableToCheck"}
/>
@Tomasz Mularczyk는 리액트 훅을 그의 답변에 언급하고 있지만, 나는 최근에 사용한 솔루션을 단지 그 솔루션만을 사용하고 싶다고 생각했다.useState
갈고리를 채우다
function Radio() {
const [currentRadioValue, setCurrentRadioValue] = useState()
const handleRadioChange = (e) => {
setCurrentValue(e.target.value);
};
return (
<>
<div>
<input
id="radio-item-1"
name="radio-item-1"
type="radio"
value="radio-1"
onChange={handleRadioChange}
checked={currentRadioValue === 'radio-1'}
/>
<label htmlFor="radio-item-1">Radio Item 1</label>
</div>
<div>
<input
id="radio-item-2"
name="radio-item-2"
type="radio"
value="radio-2"
onChange={handleRadioChange}
checked={currentRadioValue === 'radio-2'}
/>
<label htmlFor="radio-item-2">
Radio Item 1
</label>
</div>
</>
);
}
라디오 버튼을 클릭하면 다음 중 하나의 이벤트가 트리거됩니다.
- 선택지식을 로컬로만 하는 경우 setState를 호출합니다.
- 위에서 전달된 콜백을 호출한다.
self.props.selectionChanged(...)
첫 번째 경우 상태 변경은 재렌더를 트리거하고 다음을 수행할 수 있습니다.
<td>chosen site name {this.state.chosenSiteName} </td>
두 번째 경우 콜백의 소스는 SearchResult 인스턴스가 siteName과 chooseAddress를 소품으로 설정하도록 상황을 업데이트합니다.
라디오, 체크박스 구현에서도 혼란스러웠습니다.필요한 것은 라디오의 이벤트를 듣고 상태를 설정하는 것입니다.나는 성별 선택에 대한 작은 예를 들었다.
/*
* A simple React component
*/
class App extends React.Component {
constructor(params) {
super(params)
// initial gender state set from props
this.state = {
gender: this.props.gender
}
this.setGender = this.setGender.bind(this)
}
setGender(e) {
this.setState({
gender: e.target.value
})
}
render() {
const {gender} = this.state
return <div>
Gender:
<div>
<input type="radio" checked={gender == "male"}
onClick={this.setGender} value="male" /> Male
<input type="radio" checked={gender == "female"}
onClick={this.setGender} value="female" /> Female
</div>
{ "Select Gender: " } {gender}
</div>;
}
}
/*
* Render the above component into the div#app
*/
ReactDOM.render(<App gender="male" />, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
ChinKang의 답변에 근거해 말하자면, 저는 좀 더 드라이한 접근법을 가지고 있으며, 관심이 있는 분들을 위해 es6를 제안합니다.
class RadioExample extends React.Component {
constructor(props) {
super(props);
this.state = {
selectedRadio: 'public'
};
}
handleRadioChange = (event) => {
this.setState({
selectedRadio: event.currentTarget.value
})
};
render() {
return (
<div className="radio-row">
<div className="input-row">
<input
type="radio"
name="public"
value="public"
checked={this.state.selectedRadio === 'public'}
onChange={this.handleRadioChange}
/>
<label htmlFor="public">Public</label>
</div>
<div className="input-row">
<input
type="radio"
name="private"
value="private"
checked={this.state.selectedRadio === 'private'}
onChange={this.handleRadioChange}
/>
<label htmlFor="private">Private</label>
</div>
</div>
)
}
}
단, 이 값은 기본적으로 선택되어 있습니다.
부트스트랩 여러분, 우리는 이렇게 합니다.
export default function RadioButton({ onChange, option }) {
const handleChange = event => {
onChange(event.target.value)
}
return (
<>
<div className="custom-control custom-radio">
<input
type="radio"
id={ option.option }
name="customRadio"
className="custom-control-input"
onChange={ handleChange }
value = { option.id }
/>
<label
className="custom-control-label"
htmlFor={ option.option }
>
{ option.option }
</label>
</div>
</>
)
}
import React from 'react';
import './style.css';
export default function App() {
const [currentRadioValue, setCurrentValue] = React.useState('on');
const handleRadioChange = value => {
setCurrentValue(value);
};
return (
<div>
<>
<div>
<input
name="radio-item-1"
value="on"
type="radio"
onChange={e => setCurrentValue(e.target.value)}
defaultChecked={currentRadioValue === 'on'}
/>
<label htmlFor="radio-item-1">Radio Item 1</label>
{currentRadioValue === 'on' && <div>one</div>}
</div>
<div>
<input
name="radio-item-1"
value="off"
type="radio"
onChange={e => setCurrentValue(e.target.value)}
defaultChecked={currentRadioValue === 'off'}
/>
<label htmlFor="radio-item-2">Radio Item 2</label>
{currentRadioValue === 'off' && <div>two</div>}
</div>
</>
</div>
);
}
작업 예: https://stackblitz.com/edit/react-ovnv2b
언급URL : https://stackoverflow.com/questions/27784212/how-to-use-radio-buttons-in-reactjs
'programing' 카테고리의 다른 글
값을 구문 분석하는 동안 예기치 않은 문자가 발견되었습니다. (0) | 2023.04.04 |
---|---|
커스텀 포스트 타입 퍼멀링크에 커스텀 분류법을 추가하는 방법 (0) | 2023.04.04 |
Bootstrap-ui 모달과 함께 ui 라우터 사용 (0) | 2023.04.04 |
임시 업로드 위치 [/tmp/tomcat.4296537502689403143.5000/work/Tomcat/localhost/ROOT]가 잘못되었습니다. (0) | 2023.04.04 |
각도 ng-repeat vs data-ng-repeat (0) | 2023.04.04 |