在转移到另一个组件的另一个函数中调用一个函数

时间:2019-07-11 20:08:28

标签: javascript reactjs

我的目标是通过单击组件performSearch ()中的div来调用函数ItemperformSerach ()函数位于另一个select ()函数中。 select ()函数将传递给Item组件。在console.log中返回active = null

项目

class Items extends Component {
  constructor (props) {
    super(props);
    this.state = {
      items: [],
      active: null,
            abc: null
    }
  }

  select = (id) => {
    this.setState({
            abc: id
    })
    this.performSearch(id);
  }

  componentDidMount() {
    axios.get
        axios({
            url,
            method: "GET",
            headers: {
              'Authorization': `Bearer ${token}`
            }
        })
        .then(res => {
            this.setState({
              items: res.data 
            });
        })
        .catch(error => {
            console.log(error);
        })      
}

performSearch = (id) => {
  axios.get
    axios({
        url: `https://app.com/api/v1/${id}`,
        method: "GET",
        headers: {
          'Authorization': `Bearer ${token}`           
        }
    })
    .then(res => {
        this.setState({
            active: res.data
        });
    })
    .catch(error => {
        console.log(error);
    })
}

  render () {
    <div>
            {this.state.items.map((item, index) => 
                <Item
                        select={this.select}
                />
            )} 
    </div>
  }
}

项目

class Item extends Component {
  render () {
    return (
      <div onClick={()=> this.props.select(this.props.item.id)}>

      </div>
    )
  } 
}

1 个答案:

答案 0 :(得分:1)

  render () {
    <div>
            {this.state.items.map((item, index) => 
                <Item
                        select={this.select}
                />
            )} 
    </div>
  }

应将项目传递Item组件:

  render () {
    <div>
            {this.state.items.map((item, index) => 
                <Item
                        select={this.select}
                        item={item}
                        key={index}
                />
            )} 
    </div>
  }

或者:

  render () {
    <div>
            {this.state.items.map((item, index) => 
                <Item
                        select={() => this.select(item.id)}
                />
            )} 
    </div>
  }