将值从Button传递到数组

时间:2017-05-31 03:49:28

标签: reactjs

我正在尝试在数组中创建布尔过滤器。

  1. 如果按钮为“活动”(True),则应将按钮名称添加到数组中(“已选择”)。

  2. 如果按钮为“非活动”(false),则应将其从阵列中删除。

  3. 但是,只有某些值最终处于设置状态。我把它放在一个codepen中: https://codesandbox.io/s/wpxD35Oog

    import React from 'react';
    import { render } from 'react-dom';
    import { x } from './data.js';
    
    class App extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          movies: x.movies,
        };
      }
      render() {
        const uniqueGenres = []
          .concat(
            ...this.state.movies.map(movies =>
              movies.genres.map(genres => genres.name),
            ),
          )
          .filter((genre, i, _) => _.indexOf(genre) === i);
        return (
          <div>
            <div>
              {uniqueGenres.map(e => <Filter1 key={e} result={e} />)}
              <br />
            </div>
          </div>
        );
      }
    }
    
    class Filter1 extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          active: true,
          selected: '',
        };
      }
      handleActive = e => {
    //     this.setState(previousState => ({
    //     selected: [...previousState.selected, e.target.value]
    // }));
        console.log('pre-setState', e.target.value);
        const active = !this.state.active;
        const selected = e.target.value;
        this.setState({
          active: active,
          selected: selected,
        });
        console.log('status', this.state.active, this.state.selected);
      };
      render() {
        return (
          <span>
          <button onClick={this.handleActive} value={this.props.result}>
            {this.props.result} {}<b>
              {this.state.active ? 'Active' : 'Inactive'}
            </b>
    
          </button>
          </span>
        );
      }
    }
    

1 个答案:

答案 0 :(得分:1)

理想情况下,您可以让父组件(在本例中为 App )负责管理活动类型。我重写了部分代码来演示它:https://codesandbox.io/s/JZWp1RQED