我试图调用一个函数,以响应本机映射每个元素。该函数随机确定渲染组件的属性,以便renderComponent中的每个组件都是不同的。 Item是renderComponent占用的参数,i也是如此。

旁注:我尝试使用状态,但是您不能循环状态并连续更改其值。

cont randomNumber =  Math.floor(Math.random() * 3);
class whatever extends Component {
  change() {
   const randomNumber = Math.floor(Math.random() * 3);
 }

   renderComponent() {
    if(randomNumber === 0) {
     // Some cool code to set a random properties to the component
    } else if (randomNumber === 1) {
    // Same thing here and so on and so forth
    }
 }
  render() {
   return this.props.data.map(this.change.bind(this), (item, i)=> {
     return ({this.renderComponent(item)});
   }
 }
}


但是当我尝试这样做时,我只是一片空白,该组件无法渲染,因为我认为item作为参数未传递

最佳答案

我认为您要使用的是在每次迭代中都映射有项目的函数。重组您的功能使其更像

return this.props.data.map((item, i) => {
   this.renderComponent(item)
})


您的change函数应该返回一个可以从renderComponent访问的值

不能在定义它的范围之外访问randomnumber常量。将您的随机数声明为可以更改的变量之外的其他变量,或者声明为可以从renderComponent函数访问的状态对象中的键将非常有用。基本上,您的三个功能应该是

change(){this.setState({randomNum: Math.floor(Math.random() * 3) })}

renderComponent(){this.state.randomNum === 0 ? "do something" : "do something else"}

return this.props.data.map((item, i) => {
this.change() //calling this function to keep changing the number held at the state
   this.renderComponent(item)
})


别忘了初始化randomNum的状态键

10-05 21:08
查看更多