【问题标题】:React js single function with multiple setstate具有多个 setstate 的 React js 单个函数
【发布时间】:2019-03-15 23:35:42
【问题描述】:

按钮组件(子)

export default class Button extends React.Component {
  render() {
    var handleToUpdate = this.props.handleToUpdate;
    return (
      <button onClick={() => handleToUpdate(this.id)}>
        {this.props.title}
      </button>
    );
  }
}

索引(父)
作为回报

<Button title={title1} handleToUpdate={handleToUpdate.bind(this)} />
<Button title={title2} handleToUpdate={handleToUpdate1.bind(this)} />
<Button title={title3} />
<Button title={title4} />

在渲染中

const title1 = "test1"
const title2 = "test2"
const title3 = "test3"
const title4 = "test4"
var handleToUpdate = this.handleToUpdate;
var handleToUpdate1 = this.handleToUpdate1;

功能

  handleToUpdate() {
  this.setState({})
  }

  handleToUpdate1() {
  this.setState({})
  }

var handleToUpdate = this.handleToUpdate.bind(this);
var handleToUpdate1 = this.handleToUpdate1.bind(this);

我的代码没有问题,但我认为我处理该函数的方式不是好的做法。

我在这里做的是我制作了按钮组件(子)并在父(索引)中调用它四次。我创建了onClick props 来调用函数,然后设置状态。

是否有任何替代方法可以使用 4 setState 创建一个函数并根据单击的按钮 ID 调用状态。

为了更清楚。

单击按钮 1 => 调用 singlefunction => setstate1

单击按钮 2 => cal singlefunction => setstate 2 ...

【问题讨论】:

  • 可以将按钮点击事件传递给handToUpdate函数,然后通过switch语句判断哪个按钮被点击,然后设置相应的状态?
  • @AshleyBrown 能否提供一段代码或相同的示例。请
  • 完成,看看我的答案。
  • id 保存在哪里?
  • 将其存储在单个按钮上?我以为你已经设置好了,因为你通过了(this.id)

标签: javascript reactjs


【解决方案1】:

如果您将id 传递给Button 组件,这是一种替代方法。

const buttons = [
  { id: 1, title: "test1" },
  { id: 2, title: "test2" },
  { id: 3, title: "test3" },
];

class App extends React.Component {
  state = {
    clicked: "",
  };

  onUpdate = ( id ) => {
    this.setState( { clicked: id } );
  };

  render() {
    console.log( this.state );
    return (
      <div>
        {buttons.map( button => (
          <Button
            key={button.id}
            button={button}
            onUpdate={this.onUpdate}
          />
        ) )}
      </div>
    );
  }
}

const Button = ( props ) => {
  const { button, onUpdate } = props;
  const handleUpdate = () => onUpdate( button.id );
  return <button onClick={handleUpdate}>{button.title}</button>;
};

ReactDOM.render( <App />, document.getElementById( "root" ) );
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

【讨论】:

  • 为什么要创建一个带有 id 的对象?每个数组成员都已经有一个索引。
  • 索引不是每次都好。我知道这里的顺序可能不会改变,所以使用索引会很好,但如果我创建自己的列表,我更喜欢使用 id。
  • 这很公平,但到那时为什么不直接使用标题呢?
  • 如果您要求key,因为代码只是假的,我不能确定标题是否唯一。这只是一个例子:)
  • 啊,如果我对这个项目进行一些操作,处理ids比处理索引容易。一个filter 就足够了。查找索引没有任何麻烦。
【解决方案2】:

我会这样做:

render(){
    const titles = ['title1', 'title2', 'title3', 'title4'];

  return(
    {
     titles.map((title, i)=>(
     <Button title={title} key={i} 
             handleToUpdate={()=>this.handleToUpdate(i)} />
               ))
    }
} 

在您的handleToUpdate 函数/方法中,您应该使用参数i 来确定要执行的操作。您也可以使用(e)=&gt;this.handleToUpdate(e) 之类的参数,然后使用标题命名按钮并通过e.target 访问名称,如下所示:

handleToUpdate(e){
   const {name} = e.target;
   this.setState({[name]: true});
}

您可以将设置状态中的true 替换为您想要的任何内容,但是如果您正在执行具有单一潜在结果的操作,则最好使用布尔值,即始终以与您在问题中提出的方式相同的方式设置状态。

要在按钮位置不同的情况下直接传递带有 id 的函数,请执行以下操作:

<Button title={title1} handleToUpdate={()=>this.handleToUpdate(1)} />

其中1 是一个索引,其中包含任何用于插件的数字,或用于在 switch 语句中使用的任何键。

在您的 Button 组件中,将 onClick 更改为:

<button onClick={this.props.handleToUpdate}> {this.props.title} </button>

您基本上是直接将参数绑定到函数,就像我上面的 map 函数一样。

使用此解决方案,您可以像 Ashley Brown 的回答中那样执行 switch 语句。

【讨论】:

    【解决方案3】:

    您可以使用开关来根据您传入的id 确定单击了哪个按钮...或者,如果您尚未传入id,您也可以在事件中通过。如果您还没有设置道具,请务必设置...

    export default class Button extends React.Component {
      render() {
        var handleToUpdate = this.props.handleToUpdate;
        return (
          <button onClick={() => handleToUpdate(this.id)}> // <- this id you passed in
            {this.props.title}
          </button>
        );
      }
    }
    
    
    <Button id={1} title={title1} handleToUpdate={handleToUpdate.bind(this)} />
    <Button id={2} title={title2} handleToUpdate={handleToUpdate.bind(this)} />
    
    handleToUpdate(id) { // <-- id passed in
      switch(id) {
       case 1: // if id === 1
        //setState({})
       break;
    
       case 2: // if id === 2
        //setState({})
       break;
       // etc
     } 
    }
    

    【讨论】:

    • 如果 title 属性是唯一的,您可以将其传递给 onClick 函数,否则请遵循此模式。
    • @Ashley Brown 无法在 switch 语句中获取 ID。在控制台中显示未定义。
    • 这可能与this.id有关,我一目了然。
    • @DavidKamer 我相信是这样,但我喜欢使用 switch 语句的方法。有什么方法可以在 switch 语句中获取 ID 值。
    • @contactdummy 查看我的答案并将您的 id 传递给按钮,就像我展示的那样。如果您不关心问题的后半部分,请忽略它。
    猜你喜欢
    • 2020-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-14
    • 2018-04-25
    • 2014-03-24
    • 1970-01-01
    相关资源
    最近更新 更多