鍍金池/ 問答/HTML/ React 可選擇性的使用自有 state 或者 props 元件

React 可選擇性的使用自有 state 或者 props 元件

我想做一個如果有 props有value傳入,就使用 props的value,沒有傳入的話,就使用自有狀態(tài)的 <MyInput /> 元件 代碼如下

DEMO: https://stackblitz.com/edit/r...

import React from 'react';

export default class MyInput extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: (typeof this.props.value === 'string') ? this.props.value : ''
    }
  }
  componentWillReceiveProps(nextProps) {
    if ((typeof this.props.value === 'string') ? this.props.value : '') {
      this.setState({ value: nextProps.value })
    }
  }

  handleChange = (e) => {
    if (this.props.onChange) {
      this.props.onChange(e);
    } else {
      this.setState({ value: e.target.value });
    }

  }
  handleClick = (e) => {
    if (this.props.onClick) {
      this.props.onClick(e);
    } else {

    }
  }

  render() {
    return <input value={this.state.value} onClick={this.handleClick} onChange={this.handleChange} />
  }
}

但我認為這樣的代碼有點冗長,似乎考慮不周,請問有沒有這種元件的比較好的寫法可以推薦呢?

回答
編輯回答
苦妄

首先,不要在constructor()方法中,使用this.props,這個寫法在IE下無法兼容。

其次,componentWillReceiveProps()方法,將會廢棄。

可以做如下的修改:

  render() {
    const {value = this.state.value} = this.props;
    return <input value={value} />
  }

你的需求是項目中最常見的使用方式:

import React from 'react';

export default class MyInput extends React.Component {
  constructor(props) {
    super(props);
    this.state = { value: '' };
  }

  handleChange = (e) => {
    if (this.props.onChange) {
      this.props.onChange(e);
    } else {
      this.setState({ value: e.target.value });
    }

  }
  handleClick = (e) => {
    if (this.props.onClick) {
      this.props.onClick(e);
    } else {

    }
  }

  render() {
    const {value = this.state.value} = this.props;
    return <input value={value} onClick={this.handleClick} onChange={this.handleChange} />
  }
}
2018年5月15日 17:37
編輯回答
祉小皓
import React from 'react';

export default class MyInput extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: ''
    }
  }


  handleChange = (e) => {
    if (this.props.onChange) {
      this.props.onChange(e);
    } else {
      this.setState({ value: e.target.value });
    }

  }
  handleClick = (e) => {
    if (this.props.onClick) {
      this.props.onClick(e);
    } else {

    }
  }

  render() {
    return <input value={(typeof this.props.value === 'string') ? this.props.value :this.state.value} onClick={this.handleClick} onChange={this.handleChange} />
  }
}
2018年3月26日 18:57