React에서 양식 레이블의 고유 ID를 생성하는 방법은 무엇입니까?
labels 가있는 양식 요소가 있고 s label를 htmlFor속성 이있는 요소 에 연결하는 고유 ID를 갖고 싶습니다 . 이 같은 :
React.createClass({
render() {
const id = ???;
return (
<label htmlFor={id}>My label</label>
<input id={id} type="text"/>
);
}
});
이전에 ID를 생성하는 데 사용 this._rootNodeID했지만 React 0.13 이후 사용할 수 없습니다. 지금하는 가장 좋은 방법은 무엇입니까?
이 솔루션은 저에게 잘 작동합니다.
utils/newid.js:
let lastId = 0;
export default function(prefix='id') {
lastId++;
return `${prefix}${lastId}`;
}
그리고 나는 다음과 같이 사용할 수 있습니다.
import newId from '../utils/newid';
React.createClass({
componentWillMount() {
this.id = newId();
},
render() {
return (
<label htmlFor={this.id}>My label</label>
<input id={this.id} type="text"/>
);
}
});
그러나 동형 응용 프로그램에서는 작동하지 않습니다.
2015 년 8 월 17 일 추가됨 . 사용자 정의 newId 함수 대신 lodash 에서 uniqueId 를 사용할 수 있습니다 .
2016 년 1 월 28 일 업데이트 . 에서 ID를 생성하는 것이 componentWillMount좋습니다.
ID는 내부에 배치해야
componentWillMount
(2018 업데이트) constructor,하지 render. 그것을 추천 render면하게 새로운 ID를 다시 생성합니다.
밑줄이나 lodash를 사용하는 경우 uniqueId함수가 있으므로 결과 코드는 다음과 같을 것입니다.
constructor(props) {
super(props);
this.id = _.uniqueId("prefix-");
}
render() {
const id = this.id;
return (
<div>
<input id={id} type="checkbox" />
<label htmlFor={id}>label</label>
</div>
);
}
2019 후크 업데이트 :
import React, { useState } from 'react';
import _uniqueId from 'lodash/uniqueId';
const MyComponent = (props) => {
// id will be set once when the component initially renders, but never again
// (unless you assigned and called the second argument of the tuple)
const [id] = useState(_uniqueId('prefix-'));
return (
<div>
<input id={id} type="checkbox" />
<label htmlFor={id}>label</label>
</div>
);
}
2019-04-04 기준으로 React Hooks '로 달성 할 수있는 시청 광고 .useState
import React, { useState } from 'react'
import uniqueId from 'lodash/utility/uniqueId'
const Field = props => {
const [ id ] = useState(uniqueId('myprefix-'))
return (
<div>
<label htmlFor={id}>{props.label}</label>
<input id={id} type="text"/>
</div>
)
}
export default Field
내가 이해했듯이, 배열을 파괴하는 두 번째 배열 항목은 무시할 수 있습니다. id이제 구성 요소 수명 동안 다시 업데이트되지 않는 값을 얻습니다.
의 값이 id될 것이다 myprefix-<n>곳 <n>에서 리턴 증분 정수 값이다 uniqueId. 그것이 당신에게 충분히 독특하지 않다면, 당신 만의 것을 만드는 것을 고려하십시오.
function gen4() {
return Math.random().toString(16).slice(-4)
}
function simpleUniqueId(prefix) {
return (prefix || '').concat([
gen4(),
gen4(),
gen4(),
gen4(),
gen4(),
gen4(),
gen4(),
gen4()
].join(''))
}
또는 https://github.com/rpearce/simple-uniqueid 에서 게시 한 라이브러리를 확인 하십시오 . 수백 또는 수천 개의 다른 고유 ID가 있지만 uniqueId접두사가있는 lodash 는 작업을 완료하기에 충분합니다.
업데이트 2019-07-10
@Huong Hk에게 게으른 초기 상태 를 알려준 덕분에 useState초기 마운트에서만 실행 되는 함수를 전달할 수 있습니다 .
// before
const [ id ] = useState(uniqueId('myprefix-'))
// after
const [ id ] = useState(() => uniqueId('myprefix-'))
이를 위해 node-uuid 와 같은 라이브러리를 사용하여 고유 한 ID를 얻을 수 있습니다.
다음을 사용하여 설치 :
npm install node-uuid --save
그런 다음 반응 구성 요소에 다음을 추가하십시오.
import {default as UUID} from "node-uuid";
import {default as React} from "react";
export default class MyComponent extends React.Component {
componentWillMount() {
this.id = UUID.v4();
},
render() {
return (
<div>
<label htmlFor={this.id}>My label</label>
<input id={this.id} type="text"/>
</div>
);
}
}
체크섬 문제가 처음부터 나를 이끈 이유이기 때문에 범용 / 동형 솔루션을 찾는 모든 사람에게 도움이되기를 바랍니다.
위에서 말했듯이 순차적으로 새 ID를 만드는 간단한 유틸리티를 만들었습니다. ID는 서버에서 계속 증가하고 클라이언트에서 0부터 다시 시작하기 때문에 SSR이 시작될 때마다 증가분을 재설정하기로 결정했습니다.
// utility to generate ids
let current = 0
export default function generateId (prefix) {
return `${prefix || 'id'}-${current++}`
}
export function resetIdCounter () { current = 0 }
그런 다음 루트 구성 요소의 생성자 또는 componentWillMount에서 재설정을 호출합니다. 이것은 본질적으로 각 서버 렌더링에서 서버의 JS 범위를 재설정합니다. 클라이언트에서는 효과가 없습니다.
다음과 같은 쉬운 해결책을 찾았습니다.
class ToggleSwitch extends Component {
static id;
constructor(props) {
super(props);
if (typeof ToggleSwitch.id === 'undefined') {
ToggleSwitch.id = 0;
} else {
ToggleSwitch.id += 1;
}
this.id = ToggleSwitch.id;
}
render() {
return (
<input id={`prefix-${this.id}`} />
);
}
}
typescript를 사용하는 다른 간단한 방법 :
static componentsCounter = 0;
componentDidMount() {
this.setState({ id: 'input-' + Input.componentsCounter++ });
}
필요하지 않은 경우 ID를 전혀 사용하지 말고 대신 다음과 같은 레이블로 입력을 래핑하십시오.
<label>
My Label
<input type="text"/>
</label>
그러면 고유 ID에 대해 걱정할 필요가 없습니다.
참고 URL : https://stackoverflow.com/questions/29420835/how-to-generate-unique-ids-for-form-labels-in-react
'IT' 카테고리의 다른 글
| 비 관계형 데이터베이스 디자인 (0) | 2020.07.26 |
|---|---|
| 잘못된 열거 형 값으로 int를 캐스팅하면 예외가 발생하지 않는 이유는 무엇입니까? (0) | 2020.07.26 |
| for 루프 내부의 경우 (0) | 2020.07.26 |
| Qt 5.1.1 : 플랫폼 플러그인“windows”가 없기 때문에 응용 프로그램이 시작되지 않습니다. (0) | 2020.07.26 |
| 조롱 프레임 워크에서 조롱과 감시 (0) | 2020.07.26 |