React에서 양식 레이블의 고유 ID를 생성하는 방법
i i with 、 elements 、 elements 、 elements 、 elements 、 。label
'아이디'를 링크하기 위한 .label
" " 가 붙은 htmlFor
거 요.다음과 같이 합니다.
React.createClass({
render() {
const id = ???;
return (
<label htmlFor={id}>My label</label>
<input id={id} type="text"/>
);
}
});
에는 아이디를 기반으로 요.this._rootNodeID
0.13을 반응시키다.지금 가장 좋은 방법 및/또는 간단한 방법은 무엇입니까?
ID는 다음 위치에 배치해야 합니다.
component Will Mount(컴포넌트 마운트) (2018년 갱신)constructor
아니라, 이에요.render
· ★★render
신분을 밝히다
언더스코어 또는 로다시를 사용하는 경우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 Hooks 업데이트:
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>
);
}
이 해결방법은 나에게 효과가 있다.
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
.
리액트 업데이트 18
React 18은 고유 ID를 생성하는 새로운 후크를 도입했습니다.
const id = useId();
Hook API 문서: https://reactjs.org/docs/hooks-reference.html#useid
이 예에서는 컴포넌트 내부의 후크를 호출할 수 있습니다.
import React, { useId } from 'react'
function TextField = (props) => {
// generate unique ID
const id = useId();
return (
<>
<label htmlFor={id}>My label</label>
<input id={id} type="text"/>
</>
);
}
2019-04-04 현재 후속 조치로서 리액트 훅'을 통해 이를 달성할 수 있을 것으로 보입니다.
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
,
const uniqueId = (prefix = 'id-') =>
prefix + Math.random().toString(16).slice(-4)
또한 수백, 수천 개의 고유 ID가 존재하지만 Lodash는uniqueId
프레픽스를 붙이면 작업을 완료하기에 충분합니다.
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>
);
}
}
<label>
★★★★★★★★★★★★★★★★★」<input>
소품에는 의존하지 않습니다.자동으로 생성된 고유 ID를 사용하는 대신 가장 최적의 퍼포먼스 접근방식을 사용하는 것이 좋습니다.
useRef는 다음과 같은 변환 가능한 참조 개체를 반환합니다.
.current
속성이 전달된 인수(initialValue)로 초기화됩니다.반환된 개체는 구성 요소의 전체 수명 동안 유지됩니다.
즉, 사용할 수 있습니다.useRef
소품 변경에서 재계산되지 않는 인스턴스(instance) 변수를 모방합니다. useRef
는 DOM 요소 참조에만 사용되는 것이 아닙니다.
외부 랜덤 ID 생성기 사용 예(예: loadash)
import React, { useRef } from 'react'
import uniqueId from 'lodash/utility/uniqueId'
function InputField = (props) => {
const {current: fieldId} = useRef(uniqueId('prefix-'))
return (
<div>
<input id={fieldId} type="checkbox" />
<label htmlFor={fieldId}>label</label>
</div>
);
}
단순 사용자 정의 랜덤 ID 생성기 사용 예
import React, { useRef } from 'react'
function InputField = (props) => {
const {current: fieldId} = useRef("prefix-" + (Math.random().toString(36)+'00000000000000000').slice(2, 7))
return (
<div>
<input id={fieldId} type="checkbox" />
<label htmlFor={fieldId}>label</label>
</div>
);
}
설명:
위의 랜덤 아이디(Math.random().toString(36)+'00000000000000000').slice(2, 7)
이 stackoverflow 응답에서 발신되어 항상 5글자를 보증합니다.Math.random().toString(16).slice(-4)
빈 문자열이 반환될 수 있습니다.
또, 유효한 HTML4 가 되려면 , 프리픽스가 문자로 개시할 필요가 있는 프리픽스를 사용하는 것이 중요합니다. id
Atribute value.
후크를 사용하는 Lodash가 없는 버전:
function useUniqueId() {
const [id] = useState(() => `component-${Math.random().toString(16).slice(2)}`)
return id
}
우선 체크섬 문제가 저를 여기로 이끌었기 때문에 범용/동형 솔루션을 찾는 모든 사람에게 도움이 되기를 바랍니다.
위와 같이 새로운 ID를 순차적으로 작성하는 간단한 유틸리티를 만들었습니다.서버의 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에서 reset을 호출합니다.이것에 의해, 각 서버 렌더내의 서버의 JS 스코프가 리셋 됩니다.클라이언트에서는, 어떠한 영향도 주지 않습니다(그럴 필요도 없습니다).
uniqueId 제너레이터 모듈(Typescript):
const uniqueId = ((): ((prefix: string) => string) => {
let counter = 0;
return (prefix: string): string => `${prefix}${++counter}`;
})();
export default uniqueId;
또한 top 모듈을 사용하여 원하는 ID를 생성합니다.
import React, { FC, ReactElement } from 'react'
import uniqueId from '../../modules/uniqueId';
const Component: FC = (): ReactElement => {
const [inputId] = useState(uniqueId('input-'));
return (
<label htmlFor={inputId}>
<span>text</span>
<input id={inputId} type="text" />
</label>
);
};
useId 훅이 불안정한 것을 대체합니다.useOpaqueIdentifier
반응하다서버 렌더링 및 수화 중에 안정된 ID를 생성하여 불일치를 방지합니다.
「 」의 .label
★★★★★★★★★★★★★★★★★」input
다음과 같은 라벨로 입력을 랩하는 것이 간단합니다.
import React from 'react'
const Field = props => (
<label>
<span>{props.label}</span>
<input type="text"/>
</label>
)
또한 체크박스/라디오 버튼에서 루트 요소에 패딩을 적용하면서도 클릭 입력 피드백을 받을 수 있습니다.
다음과 같은 쉬운 해결책을 찾았습니다.
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}`} />
);
}
}
필요하지 않은 경우 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
'programing' 카테고리의 다른 글
SQL Server에서의 지연 가능한 제약 조건 (0) | 2023.02.22 |
---|---|
AngularJS App: .js 파일을 index.html에 포함하는 방법 (0) | 2023.02.22 |
JAVA에서 JSONArray를 정렬하려면 어떻게 해야 합니까? (0) | 2023.02.22 |
AngularJS, Karma/Jasmine 테스트는 왜 이렇게 느리게 실행됩니까? (0) | 2023.02.22 |
ESLint 오류로 인해 create-react-app을 컴파일할 수 없습니다. (0) | 2023.02.22 |