programing

React의 이벤트 개체에서 사용자 지정 특성에 액세스하는 방법은 무엇입니까?

itsource 2023. 1. 17. 21:28
반응형

React의 이벤트 개체에서 사용자 지정 특성에 액세스하는 방법은 무엇입니까?

React는 http://facebook.github.io/react/docs/jsx-gotchas.html에서 설명하는 대로 커스텀 속성을 렌더링할 수 있습니다.

커스텀 Atribute를 사용하는 경우는, 그 앞에 data-를 붙여야 합니다.

<div data-custom-attribute="foo" />

이벤트 개체에서 액세스할 수 있는 방법을 찾을 수 없다는 점을 제외하면 좋은 소식입니다. 예:

render: function() {
...
<a data-tag={i} style={showStyle} onClick={this.removeTag}></a>
...
removeTag: function(event) {
    this.setState({inputVal: event.target????}); 
},

요소 및data-속성을 html로 미세 렌더링합니다.다음과 같은 표준 특성style로서 입수할 수 있다event.target.style좋아요. 대신event.target나는 시도했다.

 event.target.props.data.tag
 event.target.props.data["tag"]
 event.target.props["data-tag"]  
 event.target.data.tag
 event.target.data["tag"]
 event.target["data-tag"]

하나도 안 먹혔어

event.target그럼 네이티브 DOM 노드가 제공되므로 일반 DOM API를 사용하여 Atribut에 액세스해야 합니다.그 방법에 대한 문서는 다음과 같습니다.데이터 속성 사용.

어느쪽이든 상관없습니다.event.target.dataset.tag또는event.target.getAttribute('data-tag')어느쪽이든 동작합니다.

질문하신 것과는 다른 방법으로 원하는 결과를 얻을 수 있도록 하기 위해:

render: function() {
    ...
    <a data-tag={i} style={showStyle} onClick={this.removeTag.bind(null, i)}></a>
    ...
},
removeTag: function(i) {
    // do whatever
},

주의:bind()모두 javascript이기 때문에 편리한 작업을 할 수 있습니다.DOM 노드를 추적하기 위해 데이터를 DOM 노드에 첨부할 필요가 없어졌습니다.

IMO 이것은 DOM 이벤트에 의존하는 것보다 훨씬 깨끗합니다.

2017년 4월 갱신:요즘 나는 글을 쓰곤 했다.onClick={() => this.removeTag(i)}대신.bind

내가 찾은 가장 좋은 방법은 다음과 같다.

var attribute = event.target.attributes.getNamedItem('data-tag').value;

이러한 속성은 "Named NodeMap"에 저장되며 getNamed를 사용하여 쉽게 액세스할 수 있습니다.아이템 방식

또는 폐쇄를 사용할 수 있습니다.

render: function() {
...
<a data-tag={i} style={showStyle} onClick={this.removeTag(i)}></a>
...
},
removeTag: function (i) {
    return function (e) {
    // and you get both `i` and the event `e`
    }.bind(this) //important to bind function 
}
// Method inside the component
userClick(event){
 let tag = event.currentTarget.dataset.tag;
 console.log(tag); // should return Tagvalue
}
// when render element
<a data-tag="TagValue" onClick={this.userClick}>Click me</a>
<div className='btn' onClick={(e) =>
     console.log(e.currentTarget.attributes['tag'].value)}
     tag='bold'>
    <i className='fa fa-bold' />
</div>

그렇게e.currentTarget.attributes['tag'].value나에겐 통한다

React v16.1.1 (2017) 현재 공식 솔루션은 다음과 같습니다.https://reactjs.org/docs/handling-events.html#passing-arguments-to-event-handlers

TLDR: OP는 다음 작업을 수행합니다.

render: function() {
...
<a style={showStyle} onClick={(e) => this.removeTag(i, e)}></a>
...
removeTag: function(i, event) {
    this.setState({inputVal: i}); 
}

이 코드 한 줄로 문제를 해결했습니다.

event.currentTarget.getAttribute('data-tag')

다음과 같은 데이터 속성에 액세스할 수 있습니다.

event.target.dataset.tag

React에서 event.target을 사용하려고 하는데 늘 값을 찾는 사람이 있다면 이는 SyntheticEvent가 event.target을 대체했기 때문입니다.SyntheticEvent에는 event.currentTarget.getAttribute('data-username')와 같은 'currentTarget'이 저장됩니다.

https://facebook.github.io/react/docs/events.html

React는 더 많은 브라우저에서 작동하도록 이 작업을 수행하는 것 같습니다.nativeEvent 속성을 통해 이전 속성에 액세스할 수 있습니다.

event.target.dataset 객체를 사용하면 됩니다.그러면 모든 데이터 속성을 가진 개체가 제공됩니다.

React에 대해서는 모르지만 일반적으로 다음과 같은 사용자 지정 속성을 전달할 수 있습니다.

1) html 태그 내에서 data-prefix를 사용하여 새로운 속성을 정의합니다.

data-mydatafield = "asdasdasdaad"

2) javascript를 사용하여

e.target.attributes.getNamedItem("data-mydatafield").value 

dom 속성을 할당하는 대신(느리지만) 값을 매개 변수로 전달하여 실제로 핸들러를 만듭니다.

render: function() {
...
<a style={showStyle} onClick={this.removeTag(i)}></a>
...
removeTag = (customAttribute) => (event) => {
    this.setState({inputVal: customAttribute});
}

리액트에서는 html 데이터가 필요없고 함수를 사용하여 다른 함수를 반환합니다.이렇게 커스텀 파라미터 전송은 매우 간단하며 커스텀 데이터와 이벤트에 액세스할 수 있습니다.

render: function() {
...
<a style={showStyle} onClick={this.removeTag(i)}></a>
...
removeTag: (i) => (event) => {
    this.setState({inputVal: i}); 
},

방법을 사용해야 할 경우에는 모두 바인드하는 이 좋다고 생각합니다.react에 정의되어 있는 setState 메서드.구성 요소 클래스, 생성자 내부의 경우 생성자는 다음과 같아야 합니다.

    constructor() {
        super()
        //This binding removeTag is necessary to make `this` work in the callback
        this.removeTag = this.removeTag.bind(this)
    }
    removeTag(event){
        console.log(event.target)
        //use Object destructuring to fetch all element values''
        const {style, dataset} = event.target
        console.log(style)
        console.log(dataset.tag)
    }
   render() {
   ...
      <a data-tag={i} style={showStyle} onClick={this.removeTag.bind(null, i)}></a>
   ...},

오브젝트 파괴에 대한 자세한 내용은 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Object_destructuring를 참조하십시오.

이건 나한테 효과가 있었어...이 예에서 내 속성은 "attr"로 명명됩니다.

e.target.selectedOptions[0].attributes.attr.value

언급URL : https://stackoverflow.com/questions/20377837/how-to-access-custom-attributes-from-event-object-in-react

반응형