【问题标题】:React list choosing option反应列表选择选项
【发布时间】:2018-05-31 16:04:59
【问题描述】:

我有一个可以保存位置名称的位置应用程序。 我正在尝试通过单击为每个保存的位置设置一个红色边框。 它所做的是改变所有类别的边框颜色。 我该如何应用它?

class Categories extends Component {
    constructor(props) {
        super(props);
        this.state = {
            term: '',
            categories: [],
            selectedCategories: [],
            hidden: true,
            checkboxState: true
        };
    }
    toggle(e) {
        this.setState({
            checkboxState: !this.state.checkboxState
        })
    }
    onChange = (event) => {
        this.setState({ term: event.target.value });
    }
    addCategory = (event) => {
        if (this.state.term === '') {
            alert('Please name your category!')
        } else {
            event.preventDefault();
            this.setState({
                term: '',
                categories: [...this.state.categories, this.state.term]
            });
        }
    }

    render() {
        return (
            <div className="categories">
                <h1>Categories</h1>
                <div className='actions'>
                    <button className="delete" onClick={this.deleteCategory}>Delete</button>
                    <button className="edit" onClick={this.editCategory}>Edit</button>

                </div>
                <p>To add new category, please enter category name</p>
                <form className="App" onSubmit={this.addCategory}>
                    <input value={this.state.term} onChange={this.onChange} />
                    <button>Add</button>
                </form>

                {this.state.categories.map((category, index) =>
                    <button
                        key={index}
                        style={this.state.checkboxState ? { borderColor: '' } : { borderColor: 'red' }}
                        checked={this.state.isChecked}
                        onClick={this.toggle.bind(this)}>
                        {category}</button>
                )}
            </div >
        );
    }
}

我希望能够单独控制每个选定的类别,以便能够删除和编辑主题。

【问题讨论】:

  • 你能澄清一下吗?因此,如果选择了一个类别,则不应选择其他类别,对吗?这意味着他们应该有某种沟通方式。或者一些监管他们的父实体
  • 您可以通过单击选择一个类别,然后它变成了红色边框。问题是创建多个类别后,单击一个会使所有类别变为红色。
  • 这仍然没有回答一个问题。您希望一次只选择一个类别还是多个类别?如果是一个,则父容器必须管理它。
  • 一次只有一个。
  • 知道了,所以你需要一个父容器。父容器保存所有类别并将方法传递给它们的道具。当您单击类别时,您会将信息从类别传递给 parent 方法。我会写一个例子并将其发布到答案中

标签: javascript reactjs list


【解决方案1】:

您可以根据索引设置状态并检索类似的方式,

Code:
          {this.state.categories.map((category, index) =>
                        <button
                            key={index}
                            id={`checkboxState${index}`}
                            style={!this.state[`checkboxState${index}`] ? 
                             { borderColor: '' } : { border: '2px solid red' }}
                            checked={this.state.isChecked}
                            onClick={this.toggle}>
                            {category}</button>
                    )}

    You can see how I am checking the state dynamically this.state[`checkboxState${index}`] and also I have assigned an id to it.

    In toggle method:

     toggle = (e) => {
            const id = e.target.id;
            this.setState({
                [id]: !this.state[id]
            })
        }

FYI, this is a working code, you can see it 

https://codesandbox.io/s/vy3r73jkrl

Let me know if this helps you :)

【讨论】:

  • 确实如此!非常感谢 !我需要更好地理解反应:)
  • 太棒了:)。快乐的反应编码:)..很高兴帮助..你也可以投票:D
【解决方案2】:

这是一个使用反应的非常糟糕的例子。我很可能会使用this.props.children,而不是把它们塞进去。这将使其更具动态性。而不是使用州名,我们可以只使用索引。但是您会观察到,父容器通过向每个子容器传递一个方法来决定哪个子容器是红色的。单击时,子级会触发父级的方法。您实现它的方式可能千变万化,但总体思路应该可行。

class ChildContainer extends React.Component
{
  constructor(props)
  {
    super(props);

  }
  
  render() {
    let color = this.props.backgroundColor;
    return(
      <section 
        className={'child'} 
        style={{backgroundColor: color}}
        onClick={this.props.selectMe}
      >
       
      </section>
    )
  }
}

class Parent extends React.Component
{

  constructor(props)
  {
    super(props)
    
    this.state = {
      first : 'Pink',
      second : 'Pink',
      third : 'Pink',
      previous: null
    }
    this.updateChild = this.updateChild.bind(this);
  }
    
    updateChild(name)
    {
      let {state} = this;
      let previous = state.previous;
      if(previous)
      {
        state[previous] = 'Pink';
      }
      
      state[name] = 'Red';
      state.previous = name;
      this.setState(state);
    }
  
    
  render()
  {
    console.log(this)
    return(
      <section id={'parent'}>
        <ChildContainer
          selectMe={() => this.updateChild('first')}
          backgroundColor = {this.state.first}
        />
        <ChildContainer
          selectMe={() => this.updateChild('second')}
          backgroundColor = {this.state.second}
        />
        <ChildContainer
          selectMe={() => this.updateChild('third')}
          backgroundColor = {this.state.third}
        />
        
      </section>
    )
  }
}

class App extends React.Component
{
  constructor(props)
  {
    super(props)
  }
  render()

  {
    return(
      <section>
        <Parent/>
        
      </section>
    )
  }
}


React.render(<App />, document.getElementById('root'));

【讨论】:

    【解决方案3】:

    您需要跟踪每个复选框的状态,可能有一个包含所有当前选中复选框的数组。

    然后,您需要检查当前类别是否在当前检查的类别数组中,而不是 this.state.checkboxState ? { borderColor: '' } : { borderColor: 'red' } 中的 this.state.checkboxState

    希望对你有帮助

    【讨论】:

    • 我真的希望,当投票否决时说明原因。这对我和偶然发现这个问题的用户都没有帮助。
    • 我认为如果您可以根据您的解释分享示例代码,那么它可能会有所帮助:D
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-19
    • 2021-08-16
    • 2019-11-08
    相关资源
    最近更新 更多