React 可选择性的使用自有 state 或者 props 元件

我想做一个如果有 props有value传入,就使用 props的value,没有传入的话,就使用自有状态的 <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} />
  }
}

但我认为这样的代码有点冗长,似乎考虑不周,请问有没有这种元件的比较好的写法可以推荐呢?

阅读 1.7k
2 个回答

首先,不要在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} />
  }
}
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} />
  }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题