javascript - 如何在 React 中设置一个类对象?

标签 javascript reactjs

我正在修改我的类中的一组对象,只有当按键发生时,我才想以可视方式呈现该对象。

class Example extends React.Component {
    constructor(props) { 
       super(props); 
       this.myArr = []; // this is an array of objects 
    }

    render() {  
       return (
        ???
       );
    }
}

现在我用很多不同的方法修改this.myArr的内容。只有当我准备好时(在按键或其他事件上)我才想渲染它。

现在在我的 render() 中,我是否应该引用 this.myArr,然后在我想强制重新渲染时使用 this.forceUpdate()

或者我应该将 myArr 移动到 this.state.myArr 中,并在我的方法中修改 this.state.myArr,当我准备好显示它时,在我的 render() 引用中修改 >this.state.myArr,并以某种方式强制重新渲染 this.setState(myArr: this.state.myArr);

最佳答案

***第二次更新 - 我认为这可能是您想要的。显然,您需要为鼠标单击事件添加大量逻辑。不过,它应该会为您指明正确的方向。

class Example extends React.Component {
  constructor(props) {
    super(props);
    this.myArr = [];

    this.state = {
      myArr: [{ width: 10 }, { width: 20 }], // header widths
    };
  }

  // call changeHeaders when needed
  // it will update state, which will cause a re-render
  changeHeaders = (column, newWidth) => {
    const newArr = [...this.state.myArr];

    if (newArr[column]) {
      newArr[column].width = newWidth;
    }

    this.setState({ myArr: newArr });
  }

  renderArray = () => {
    return this.state.myArr.map(({ width }) => <div>{width}</div>);
  }

  render() {
    return (
      <div>
        {this.renderArray()}
      </div>
    );
  }
}

关于javascript - 如何在 React 中设置一个类对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50519509/

相关文章:

javascript - Jquery 每秒选择随机单元格

javascript - 如何将 jQuery 模板集成到 React App 中

javascript - Reactjs - 我想使用一些 json-server 模拟数据来测试我的登录应用程序

javascript - 如何获取函数中未定义的参数

php - AJAX:PHP函数返回1,但 'success'部分说它返回0

javascript - Modal 中的 Bootstrap DatePicker 不起作用

javascript - 将 Ember 组件插入特定的 DOM 元素?

reactjs - 如何使用Redux Toolkit(带有TypeScript)解决 'Property '类型中缺少 'AsyncThunkAction'类型的问题?

reactjs - 如果需要在子路由上进行 react ,则路由器reux提取资源

reactjs - 这个渲染方法做了什么: const {images, selectedImage} = this.state;?