【问题标题】:Adding rendered item position to an array of items?将渲染的项目位置添加到项目数组?
【发布时间】:2018-04-29 03:24:55
【问题描述】:

我想在渲染时添加每个对象的位置坐标,以便我可以将其指定为拖放区。

我可以将一条数据放入objLocation,但显然,它会随着每个SubComponent 的呈现而不断覆盖。构建该对象位置数组的正确方法是什么?

const data = [
  { id: 1 },
  { id: 2 },
  { id: 3 },
]


export default class Viewport extends Component {
    this.state = {
      objLocation = [],
    }

    render() {
      return (
        {data.map( d => {
          return(
            <SubComponent onLayout={this.getLayout} id={d.id} />
          )
        })}
      )
    }


    getLayout = (e) => (
      const obj = { 
        width: e.nativeEvent.layout.width,
        height: e.nativeEvent.layout.height,
        x: e.nativeEvent.layout.x,
        y: e.nativeEvent.layout.y,
      }
      this.setState({
        objLocation: obj
      });
    }
}

【问题讨论】:

    标签: javascript json react-native


    【解决方案1】:

    找到答案here。

    this.setState({ 
      arrayvar: this.state.arrayvar.concat([newelement])
    })
    
    
    ES6 With Spread operator.
    this.setState({
      arrayvar: [...this.state.arrayvar, newelement]
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多