将父级组件支持给父级-子级组件

时间:2018-11-09 13:03:27

标签: reactjs

如何从子组件(卡)调用父组件(应用)中的函数?

卡片组件呈现一项(儿童

const Card = (props) => {
  return (
    <div style={{margin: '1em'}}>
      <img alt="Profile" width="75" src={props.avatar_url} />
      <div style={{display: 'inline-block', marginLeft: 10}}>
        <div style={{fontSize: '1.25em', fontWeight: 'bold'}}> 
            {props.name}
        </div>
        <div>{props.company}</div>
        <button
          //when I click here should trigger App's delete func who deletes the select item.  
          onClick = { () => alert()}
          className="btn btn-danger btn-sm">Delete</button>
      </div>
    </div>
  );
};

CardList组件呈现项目列表( CHILD-PARENT

const CardList = (props) => {
    return (
  //Props.nameProp = Value {...Card} spred operator
    <div> 
        {props.cards.map(card => <Card key={card.id} {...card} />)}
    </div>
  );
}

父组件:

class App extends React.Component {
    state = {
    cards: [
    ]
  };

  addNewCard = (cardInfo) => {
    this.setState(prevState => ({
        cards: prevState.cards.concat(cardInfo)
    }))
  };

  deleteCard = (selectedCard) => {
      this.setState(prevState => ({
        //array.filter creates a new array with elements who pass the foo
        cards: prevState.cards.filter(card => card !== selectedCard)
      }));
  }

    render(){
    const {
      cards,
    } = this.state;
    return(
        <div className="container" style={{marginTop: 15}}>
        <Form onSubmit={this.addNewCard} />        
        <div className="container" style={{padding: 20}}>
          {
            cards.length > 0 ? 
            <CardList cards={cards} />
            :
            <p>Your list is empty</p>
          }
        </div>          
        </div>
    );      
  }
}

EXPLANATION

我要删除状态列表中但该列表位于父组件中的项目,我该怎么做?

1 个答案:

答案 0 :(得分:1)

您可以将deleteCard方法作为对CardList的支持,并从CardList传递到每个Card组件,然后在其中调用。

示例

const Card = props => (
  <button onClick={() => props.deleteCard(props.card)}>{props.card}</button>
);

const CardList = props => (
  <div>
    {props.cards.map(card => (
      <Card card={card} deleteCard={props.deleteCard} />
    ))}
  </div>
);

class App extends React.Component {
  state = {
    cards: [1, 2, 3]
  };

  deleteCard = card => {
    this.setState(({ cards }) => ({
      cards: cards.filter(element => element !== card)
    }));
  };
  
  render() {
    const { cards } = this.state;
    return <CardList cards={cards} deleteCard={this.deleteCard} />;
  }
}

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="root"></div>