【问题标题】:How to render Child Component by Click event from Parent Component?如何通过父组件的 Click 事件渲染子组件?
【发布时间】:2018-01-09 04:21:50
【问题描述】:

我正在尝试通过父组件的 Click 事件来渲染子组件。 这是父组件。我在父组件中选择开始日期和结束日期。

 handleStartDateChange = (e, date) => {
    this.setState({ startDate: date });
}
 ...
 handleFilterClick = () => {
        let urlGetCashListByDate = urlGetCashList + '?starttime=' + this.state.startDate +'&endtime=' + this.state.endDate;
        let urlGetOrderListByDate = urlGetOrderList + '?starttime=' + this.state.startDate + '&endtime=' + this.state.endDate;  
 }
 render() {
 return ( 
         <DatePicker
          id="start-date"
          onChange={this.handleStartDateChange}/>)
         <DatePicker
          id="end-date"
          hintText="End Date"
          onChange={this.handleEndDateChange}/>
         <RaisedButton
          onClick={this.handleFilterClick}/> 

         <OrderList/>
         <CashList/>        
 )}

这是子组件:

class OrderList extends Component{
    componentDidMount(){
       this.props.getOrderList(urlGetOrderList);
}

和 CashList 子组件:

class CashList extends Component{
        componentDidMount(){
           this.props.getCashList(urlGetCashList);
}

如何像这样使用父组件的新 URL 来渲染子组件? (在 CashList 组件中)

this.props.getCashList(urlGetCashListByDate)

我知道passing a state,但我的问题是 url。 谢谢。

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    使用相同的 urlGetOrderListurlGetCashList 变量,假设它们在某处定义(它们应该对应于任一查询的基本 URL):

    constructor(props) {
      super(props);
    
      this.state = {
        startDate: null,
        endDate: null,
        ...
        urlParams: ''
      };
    }
    
    handleStartDateChange = (e, startDate) => {
      this.setState({ startDate });
    }
    ...
    handleFilterClick = () => {
      this.setState({ urlParams: `?starttime=${this.state.startDate}&endtime=${this.state.endDate}` });
    }
    render() {
      return ( 
        <DatePicker
          id="start-date"
          onChange={this.handleStartDateChange} />
        <DatePicker
          id="end-date"
          hintText="End Date"
          onChange={this.handleEndDateChange} />
        <RaisedButton
          onClick={this.handleFilterClick} /> 
    
        <OrderList url={urlGetOrderList + this.state.urlParams} />
        <CashList url={urlGetCashList + this.state.urlParams} />        
      );
    }
    

    在您的 OrderList 组件中:

    class OrderList extends Component {
      ...
      retrieveList(url) {
        this.props.getOrderList(url);
      }
      componentDidMount() {
        this.retrieveList(this.props.url);
      }
      componentWillReceiveProps(nextProps) {
        if (nextProps.url !== this.props.url) {
          this.retrieveList(nextProps.url);
        }
      }
    }
    

    在您的 CashList 组件中也是如此。

    【讨论】:

      猜你喜欢
      • 2019-12-04
      • 1970-01-01
      • 2018-03-03
      • 2018-05-05
      • 2012-09-16
      • 1970-01-01
      • 1970-01-01
      • 2019-06-20
      • 1970-01-01
      相关资源
      最近更新 更多