React - 在这种情况下,如何在Input组件中设置state?

时间:2018-02-09 03:14:40

标签: javascript reactjs

我有两个组件:InputButtons

Input代码:

import React, { Component } from 'react';
import TextField from 'material-ui/TextField';
import './style.css';

import Buttons from '../Buttons';

class Input extends Component {
  constructor(props) {
    super(props);
    this.state = {
      password: '',
      selectedButtons: [],
    };
  }

  handleInputChange(pass) {
    this.setState({ password: pass });
  }

  handleButtonSelectTwo(selected) {
    // this.setState({ selectedButtons: selected });
    console.log(selected);
  }

  render() {
    return (
      <div>
        <div className="Input-textfield">
          <TextField
            hintText="Paste your password here to begin"
            value={this.state.password}
            onChange={event => this.handleInputChange(event.target.value)}
          />
        </div>
        <div>
          <Buttons handleButtonSelectOne={this.handleButtonSelectTwo} />
        </div>
      </div>
    );
  }
}
export default Input;

Buttons代码:

import React from 'react';
import RaisedButton from 'material-ui/RaisedButton';

const style = {
  button: {
    margin: 2,
    padding: 0,
    minWidth: 1,
  },
};

const Buttons = props => {
  const arr = [
    1,
    2,
    3,
    4,
    5,
    6,
    7,
    8,
    9,
    10,
    11,
    12,
    13,
    14,
    15,
    16,
    17,
    18,
    19,
    20,
  ];

  const handleButtonSelectZero = props.handleButtonSelectOne;

  const allButtons = arr.map(el => (
    <RaisedButton
      key={el}
      label={el}
      style={style.button}
      onClick={() => handleButtonSelectZero(el)}
    />
  ));

  return <div>{allButtons}</div>;
};

export default Buttons;

问题是handleButtonSelectTwo功能。所以使用console.log,它可以工作。当我点击例如11号按钮时,它打印到控制台&#39; 11&#39;。所以我理解的方式是handleButtonSelectTwo函数作为一个道具传递给Buttons孩子并在那里被解雇。

在这种情况下,如果我现在要将此类代码添加到handleButtonSelectTwo组件内的Input

  handleButtonSelectTwo(selected) {
    this.setState({ selectedButtons: selected });
  }

它将无法工作,因为它将在Buttons组件内被触发,该组件是无状态组件。

因此,如果我想在我的Input组件中点击数据,我该怎么办呢?

在我的Input组件中,我的状态如下:

  constructor(props) {
    super(props);
    this.state = {
      password: '',
      selectedButtons: [],
    };
  }

我希望它被我点击的按钮填充。

有一些简单的方法吗? (例如,不使用redux)

1 个答案:

答案 0 :(得分:1)

您可能希望将handleButtonSelectTwo绑定到正确的this。在Input组件的构造函数中输入this.handleButtonSelectTwo = this.handleButtonSelectTwo.bind(this)