繁体   English   中英

当父组件状态更改时,将类添加到子组件

[英]Add a class to child component when parent component state changes

这是我第一次尝试使用React构建。 我通常使用jQuery或普通的旧JS编写UI交互。 我只是想要一个文本字段,当输入文本时,它会添加一个类,以便可以将其样式设置为默认状态。 注意我只希望在输入至少一个字符时添加此类,而不是在字段集中时添加。

我已经在子组件中具有onChange函数,该函数用于更改'textEntered'的状态,但是我不知道如何在子组件中利用此状态添加类。

这是我的父组件

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import TextInput from './components/TextInput/TextInput';

export default class Form extends Component {
  constructor(props) {
    super(props);
    this.state = {
      textEntered: '',
      completed: false,
    };
  }

  render() {
    return (
      <div>
        <TextInput
          placeholderText={'Title'}
          updateText={textEntered => this.setState({ textEntered })}
          completed={this.state.completed}
        />
      </div>
    );
  }
}

ReactDOM.render(<Form />, document.getElementById('react-create-form'));

这是子组件

import React, { PropTypes } from 'react';

const TextInput = props => (
  <div>
    <input
      type={props.type}
      placeholder={props.placeholderText}
      onChange={e => props.updateText(e.target.value)}
      data-completed={props.completed}
    />
  </div>
);

TextInput.propTypes = {
  type: PropTypes.string,
  placeholderText: PropTypes.string,
  updateText: PropTypes.func,
  completed: PropTypes.bool,
};

TextInput.defaultProps = {
  type: 'text',
};

export default TextInput;

从父组件传递类名,然后进行检查。 如果文本字段至少包含一个字符,则传递实际的类名,否则为空白字符串。

由于您将文本字段的值存储在父组件的状态内部,因此将条件设置如下:

customClass = {this.state.textEntered.length ? 'actualClassName': ''}

码:

<div>
    <TextInput
        customClass={this.state.textEntered.length ? 'actualClassName': ''}
        placeholderText={'Title'}
        updateText={textEntered => this.setState({ textEntered })}
        completed={this.state.completed}
    />
</div>

在子组件内部,应用此customClass。

const TextInput = props => (
    <div>
        <input
            type={props.type}
            className={props.customClass}
            placeholder={props.placeholderText}
            onChange={e => props.updateText(e.target.value)}
            data-completed={props.completed}
        />
    </div>
);

注意:另一种方法是,在props中传递值,而不是传递类名,并将条件直接放在子组件中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM