首页 > 解决方案 > 从子组件访问 this.state 值

问题描述

我无法将日期值从react-dates组件传递到它的父组件。

首先,我通常会使用Redux来处理这样的任务,但这对项目来说太过分了,我更喜欢简单的解决方案。

如何将onChange事件从DateRangePicker它的父组件传递?

父组件

...    
import DateRangePicker from './DatepickerRates'

class Rates extends Component {
    constructor(props) {
        super(props);
        this.state = { }
    }

    onChange(startDate, endDate) {
        this.setState({[startDate]: startDate});
        this.setState({[endDate]: endDate});
    }

    render() {
        console.log(`In ${this.state.startDate} - Out ${this.state.endDate}`)

        return (
            <Wrapper>
              <DateRangePicker onChange={this.onChange.bind(this)}/>
            </Wrapper>
        );
    }
}
export default Rates;

日期范围选择器

...
class DateRangePickerWrapper extends Component {
    constructor(props) {
        super(props);
        this.state = {
            focusedInput,
            startDate: props.initialStartDate,
            endDate: props.initialEndDate,
        }
        this.onDatesChange = this.onDatesChange.bind(this);
        this.onFocusChange = this.onFocusChange.bind(this);
    }

    onDatesChange({ startDate, endDate }) {
        const { stateDateWrapper } = this.props;
        this.props.onChange('startDate', this.state.startDate);
        this.props.onChange('endDate', this.state.endDate);
        this.setState({
          startDate: startDate && stateDateWrapper(startDate),
          endDate: endDate && stateDateWrapper(endDate),
        });
    }

    render() {
        const { startDate, endDate } = this.state;

        ...

        return (
            <div>
                <DateRangePicker
                    {...props}
                    onDatesChange={this.onDatesChange}
                    onFocusChange={this.onFocusChange}
                    focusedInput={focusedInput}
                    startDate={startDate}
                    endDate={endDate}
                />
            </div>
        );
    }
}

export default DateRangePickerWrapper;

标签: javascriptreactjsreact-dates

解决方案


这是工作演示 - https://codesandbox.io/s/vqw83my5l0 在您的父组件上设置一个道具 onChange={this.handleDropDownChange},例如在子组件中 onChange of date,在 onDatesChangeand 函数集中 this.props.onChange(startDate, endDate),您将获得数据handleDropDownChange()


推荐阅读