javascript React부모에게서메소드받아서실행(来自道具的事件方法)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript React부모에게서메소드받아서실행(来自道具的事件方法)相关的知识,希望对你有一定的参考价值。

import React, { Component } from "react";
import NumberItem from "./NumberItem";

export default class NumberList extends Component {
  constructor(props) {
    super(props);
    this.state = { nums: [1, 2, 3, 4, 5] };
  }

  remove(num) {
    this.setState(st => ({
      nums: st.nums.filter(n => n !== num)
    }));
  }

  render() {
    let nums = this.state.nums.map(n => (
      <NumberItem value={n} remove={() => this.remove(n)} />
    ));
    return (
      <div>
        <h1>First Number List</h1>
        <ul>{nums}</ul>
      </div>
    );
  }
}

import React, { Component } from "react";
import NumberItem from "./NumberItem";

export default class NumberList extends Component {
  constructor(props) {
    super(props);
    this.state = { nums: [1, 2, 3, 4, 5] };
  }

  remove(num) {
    this.setState(st => ({
      nums: st.nums.filter(n => n !== num)
    }));
  }

  render() {
    let nums = this.state.nums.map(n => (
      <NumberItem value={n} remove={() => this.remove(n)} />
    ));
    return (
      <div>
        <h1>First Number List</h1>
        <ul>{nums}</ul>
      </div>
    );
  }
}


import React, { Component } from "react";
import BetterNumberItem from "./BetterNumberItem";

export default class BetterNumberList extends Component {
  constructor(props) {
    super(props);
    this.state = { nums: [1, 2, 3, 4, 5] };
    this.remove = this.remove.bind(this);
  }

  remove(num) {
    console.log("Removing");
    console.log(num);
    this.setState(st => ({
      nums: st.nums.filter(n => n !== num)
    }));
  }

  render() {
    let nums = this.state.nums.map(n => (
      <BetterNumberItem value={n} remove={this.remove} />
    ));
    return (
      <div>
        <h1>First Number List</h1>
        <ul>{nums}</ul>
      </div>
    );
  }
}


import React, { Component } from "react";

export default class BetterNumberItem extends Component {
  constructor(props) {
    super(props);
    this.handleRemove = this.handleRemove.bind(this);
  }

  handleRemove(evt) {
    this.props.remove(this.props.value);
  }

  render() {
    return (
      <li>
        {this.props.value}
        <button onClick={this.handleRemove}>X</button>
      </li>
    );
  }
}

以上是关于javascript React부모에게서메소드받아서실행(来自道具的事件方法)的主要内容,如果未能解决你的问题,请参考以下文章

javascript React hooks에서이전결과값받아올때

三和 韓長庚 先生의 寫眞

javascript 위젯내에서ajax call로생기는요소에대응하는js

javascript Javascript删除特定阵列(자바스크립트에서배열요소삭제)

javascript 모바일에서'더보기'눌렀을때리뷰수갱신

javascript 고도몰이나기타솔루션사에서모바일주문내기더보기버튼눌렀을때리뷰작성버튼에링크붙여주는스크립트