我对我的代码没有问题,我只是为了学习目的问这个问题,因为我已经学习了一周半了.我的问题是,我绑定了影响/改变我的listValue和listAdd状态的函数,那么我应该绑定那些不影响我的状态的函数,比如addList()和clearList(),还是应该只在涉及到状态时绑定?此外,如果你有任何优化的建议或我可以做的不同,使它更容易,我会很高兴听到这些.

function ListApp() {
  return <List/>
}

class List extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      listValue: '',
      listAdd: ''
    }

    this.handleList = this.handleList.bind(this);
    this.addValue = this.addValue.bind(this);
  }

  handleList(){
    if(this.state.listValue !== ''){
      this.setState({
        listAdd: this.state.listValue
      }, ()=>this.addList(this.state.listAdd))
    }
    document.querySelector(".textArea").value = '';
    this.setState({
      listValue: ''
    })
  }

  addValue(event){
    this.setState({
      listValue: event.target.value
    })
  }

  addList(value){
    const node = document.createElement("li");
    const textnode = document.createTextNode(value);
    node.appendChild(textnode);
    document.querySelector(".listBox").appendChild(node);
  }

  clearList(){
    while (document.querySelector(".listBox").firstChild) { 
      document.querySelector(".listBox").firstChild.remove(); 
    }
  }

  render(){
    return(
      <div className="box1">
        <textarea placeholder="Type here" className="textArea" maxLength={68} onChange={this.addValue}></textarea>
        <button className="add" onClick={this.handleList}>Add</button>
        <button className="clear" onClick={this.clearList}>Clear</button>
        <ul className="listBox"></ul>
      </div>
    );
  }
}

推荐答案

Technically,对于你的例子来说,绑定引用this.statethis.setState()的函数就足够了,BUT你误解了原因:

您需要绑定使用this的函数,因为this总是引用当前的execution context,并且您需要在List组件的上下文中执行这些函数,以便通过this关键字引用组件的方法/属性.

但是,在分配给onClick属性的情况下,与List组件的关系"丢失".

关于执行上下文

完全相同的函数可以在不同的执行上下文中执行.例如,考虑这个例子:

const o = {
  fnct: function(){      // assign an anonymous function to `o.fnct`
    console.log( this ); // print current execution context
  }
};

const f = o.fnct; // assign the same function to `f` 

o.fnct();  // call the function in the context of `o`
f();       // call the function in the global context (`window` in the browser)

对于this,你会得到不同的输出:对象o代表o.fnct(),全局对象代表f().

如果你需要保持函数始终在o的上下文中执行(而不是当前上下文),你需要将函数绑定到o:

const fTemp = o.fnct;  // this is the "plain" original function again
const fBoundToO = ftemp.bind(o); // this is the function bound to `o`
o.fnct = fBoundToO;    // re-assign the bound function to `o.fnct`

同样可以写得更短:

o.fnct = o.fnct.bind(o);

现在你可以在其他上下文中使用这个绑定函数,但它的this仍然是o:

const f = o.fnct;  // assign the bound function to `f`
f();               // call `f()` in the global context, but inside `f` the bound context `o` is used

现在,在这两种情况下,对象o都被打印为执行上下文.

React onClick

当你在React中分配onClick={ onClickHandler }属性时,会发生与上面相同的情况:

this.onClickHandler = function(){}; // assign a function to the property `this.onClickHandler`
// ...
{
  onClick: this.onClickHandler // assign the _same_ function to `onClick`
}
// ...
List.onClickHandler();  // `this` inside the function is the List
Button.onClick();       // `this` inside the function is the Button

当执行onClick()时,它只是在任何上下文中执行该函数(e.g. the 101 React element).

但是,如果onClickHandler被绑定到List组件(102),那么它会继续使用List组件作为上下文(即this指向List组件,this.state是'theListMementInstance.state').

结论

你现在不需要绑定addList()clearList(),因为它们不使用this,所以在哪个上下文中执行它们并不重要.

但是addList()clearList()可能迟早会导致其他错误,因为它们操纵DOM,这在React中是绝对不应该做的.

Javascript相关问答推荐

使用typeof运算符获取对象值类型-接收字符串而不是数组

在JavaScript中对大型级联数组进行切片的最有效方法?

Javascript,部分重排序数组

按下同意按钮与 puppeteer 师

在JavaScript中声明自定义内置元素不起作用

React 17与React 18中的不同setState行为

Angular:动画不启动

如何从一个列表中创建一个2列的表?

为什么!逗号和空格不会作为输出返回,如果它在参数上?

显示图—如何在图例项上添加删除线效果?

在Three JS中看不到补间不透明度更改效果

从另一个数组中的对应行/键值对更新数组中的键值对对象

如何在HTMX提示符中设置默认值?

AJAX POST在控制器中返回空(ASP.NET MVC)

在渲染turbo流之后滚动到元素

在JavaScript中将Base64转换为JSON

在HTML5画布上下文中使用putImageData时,重载解析失败

为什么我的Navbar.css没有显示在本地主机页面上?

设置复选框根据选中状态输入选中值

如果查询为空,则MongoDB将所有文档与$in匹配