在React.js中获取子组件的状态

时间:2017-03-13 04:37:28

标签: javascript reactjs

使用refstate来获取子组件的值是否“好”(在React.js意义上)?或者有没有“适当的”方法来实现这一目标?

为什么我认为可能有另一种方法是ref通过state获取并直接引用他们的startDate似乎非常可疑。

我的代码如下所示。这是一个简化的。

问题是endDate_handleSubmit 只有在调用 import moment from 'moment-timezone'; import React from 'react'; import CustomDatepickerInput from './custom-datepicker-input'; class ParentWrapper extends React.Component { constructor(props) { super(props); this.state = { endDate: moment().format('YYYY-MM-DD'), startDate: moment().subtract(29, 'days').format('YYYY-MM-DD'), }; this._handleSubmit = this._handleSubmit.bind(this); } render() { // Some logics that change the view when this.state.endDate or this.state.startDate is updated. return ( <div> <div> <div> <CustomDatepickerInput date={this.state.startDate} ref={c => this._startDate = c} /> <CustomDatepickerInput date={this.state.endDate} ref={c => this._endDate = c} /> <span className="diabetes-tabs-submit" onClick={this._handleSubmit}></span> </div> </div> </div> ); } _handleSubmit() { this.setState({ startDate: moment(this._startDate.state.date).format('YYYY-MM-DD'), endDate: moment(this._endDate.state.date).format('YYYY-MM-DD'), }) } }; export default ParentWrapper; 时才能更新,因为有些逻辑可以在这两个时更改视图州更新,这是一个禁止进入的情况。

一些父-component.js

import moment from 'moment-timezone';
import Pikaday from 'pikaday';
import React from 'react';
import ReactDOM from 'react-dom';

class CustomDatepickerInput extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      date: this.props.date,
    };
  }

  componentDidMount() {
    new Pikaday({
      field: ReactDOM.findDOMNode(this),
      format: 'YYYY-MM-DD',
      onSelect: this._handleDateChange,
    });
  }

  render() {
    return (
      <input type="text" defaultValue={this.state.date} />
    );
  }

  _handleDateChange(date) {
    this.setState({date: moment(date).format('YYYY-MM-DD')});
  }
};

export default CustomDatepickerInput;

定制日期选择器-input.js

var a = "example";
var myObj = {
  Chatting: {
    a: { // here it is assumes to be "a"
      "id": a // here exapmle is being stored in to "id"
    }
  }
}

console.log(myObj["Chatting"]["a"])// will let you access it

0 个答案:

没有答案