program story

ES6 구문을 사용하여 onclick 이벤트를 통해 매개 변수를 전달하는 반응

inputbox 2020. 9. 20. 09:48
반응형

ES6 구문을 사용하여 onclick 이벤트를 통해 매개 변수를 전달하는 반응


ES6 구문을 사용하여 onClick 이벤트에 추가 매개 변수를 전달하는 방법은 무엇입니까?

예를 들면 :

handleRemove = (e) => {

}

render() {
     <button onClick={this.handleRemove}></button>
}

다음 handleRemove과 같은 함수에 ID를 전달하고 싶습니다.

<button onClick={this.handleRemove(id)}></button>

점에서 기억 onClick={ ... }의는 ...자바 스크립트 표현이다. 그래서

... onClick={this.handleRemove(id)}

와 같다

var val = this.handleRemove(id);
... onClick={val}

즉, this.handleRemove(id)즉시 호출 onClick하고 원하는 이 아닌에 해당 값을 전달합니다 .

대신 이미 미리 채워진 인수 중 하나 를 사용하여 함수 를 만들고 싶습니다 . 기본적으로 다음을 원합니다.

var newFn = function() {
  var args = Array.prototype.slice.call(arguments);

  // args[0] contains the event object
  this.handleRemove.apply(this, [id].concat(args));
}
... onClick={newFn}

이것을 ES5 JavaScript로 표현하는 방법이 있습니다 : Function.prototype.bind.

... onClick={this.handleRemove.bind(this, id)}

을 사용 React.createClass하면 React this가 인스턴스 메서드에 자동으로 바인딩 되며 this.handleRemove.bind(null, id).

단순히 함수를 인라인으로 정의 할 수도 있습니다. 환경이나 트랜스 파일러가 지원하는 경우 화살표 기능 으로 더 짧아집니다 .

... onClick={() => this.handleRemove(id)}

이벤트에 액세스해야하는 경우 다음과 같이 전달하면됩니다.

... onClick={(evt) => this.handleRemove(id, evt)}

버튼 요소 값 속성사용하여 ID를 다음과 같이 전달합니다.

<button onClick={this.handleRemove} value={id}>Remove</button>

그런 다음 handleRemove에서 이벤트의 값을 다음과 같이 읽습니다.

handleRemove(event) {
...
 remove(event.target.value);
...
}

이렇게하면이 구성 요소가 다시 렌더링 될 때마다 새 함수를 만들지 않아도됩니다 (화살표 함수를 사용하는 것과 비교할 때).


다음과 같이 Arrow 기능을 사용하십시오.

<button onClick={()=>{this.handleRemove(id)}}></button>

onClick={this.handleRemove.bind(this, id)}

지금까지 아무도 언급하지 않은 것은 handleRemove가 함수를 반환하도록 만드는 것입니다.

다음과 같이 할 수 있습니다.

handleRemove = id => event => {
  // Do stuff with id and event
}

// render...
  return <button onClick={this.handleRemove(id)} />

그러나 이러한 모든 솔루션에는 각 렌더에서 새 기능을 만드는 단점이 있습니다. 더 나은이 전달되는 버튼의 새로운 구성 요소를 생성하는 id과를 handleRemove분리합니다.


TL;DR:

Don't bind function (nor use arrow functions) inside render method. See official recommendations.

https://reactjs.org/docs/faq-functions.html


So, there's an accepted answer and a couple more that points the same. And also there are some comments preventing people from using bind within the render method, and also avoiding arrow functions there for the same reason (those functions will be created once again and again on each render). But there's no example, so I'm writing one.

Basically, you have to bind your functions in the constructor.

class Actions extends Component {

    static propTypes = {
        entity_id: PropTypes.number,
        contact_id: PropTypes.number,
        onReplace: PropTypes.func.isRequired,
        onTransfer: PropTypes.func.isRequired
    }

    constructor() {
        super();
        this.onReplace = this.onReplace.bind(this);
        this.onTransfer = this.onTransfer.bind(this);
    }

    onReplace() {
        this.props.onReplace(this.props.entity_id, this.props.contact_id);
    }

    onTransfer() {
        this.props.onTransfer(this.props.entity_id, this.props.contact_id);
    }

    render() {
        return (
            <div className="actions">
                <button className="btn btn-circle btn-icon-only btn-default"
                    onClick={this.onReplace}
                    title="Replace">
                        <i className="fa fa-refresh"></i>
                </button>
                <button className="btn btn-circle btn-icon-only btn-default"
                    onClick={this.onTransfer}
                    title="Transfer">
                    <i className="fa fa-share"></i>
                </button>                                 
            </div>
        )
    }
}

export default Actions

Key lines are:

constructor

this.onReplace = this.onReplace.bind(this);

method

onReplace() {
    this.props.onReplace(this.props.entity_id, this.props.contact_id);
}

render

onClick={this.onReplace}

I use the following code:

<Button onClick={this.onSubmit} id={item.key} value={shop.ethereum}>
    Approve
</Button>

Then inside the method:

onSubmit = async event => {
    event.preventDefault();
    event.persist();
    console.log("Param passed => Eth addrs: ", event.target.value)
    console.log("Param passed => id: ", event.target.id)
    ...
}

As a result:

Param passed in event => Eth addrs: 0x4D86c35fdC080Ce449E89C6BC058E6cc4a4D49A6

Param passed in event => id: Mlz4OTBSwcgPLBzVZ7BQbwVjGip1


I am using React-Bootstrap. The onSelect trigger for dropdowns were not allowing me to pass data. Just the event. So remember you can just set any values as attributes and pick them up from the function using javascript. Picking up those attributes you set in that event target.

    let currentTarget = event.target;
    let currentId = currentTarget.getAttribute('data-id');
    let currentValue = currentTarget.getAttribute('data-value');

참고URL : https://stackoverflow.com/questions/34350988/react-passing-parameter-via-onclick-event-using-es6-syntax

반응형