Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/cmake/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
React native undefined不是一个对象(正在按此2.setProject.bind';)_React Native - Fatal编程技术网

React native undefined不是一个对象(正在按此2.setProject.bind';)

React native undefined不是一个对象(正在按此2.setProject.bind';),react-native,React Native,React native初学者在这里,我正在尝试制作一个应用程序,当我按下自定义组件时,它会运行一个函数,但当我尝试这样做时,我得到了“undefined不是一个对象(正在计算'\u this2.setProject.bind')”错误 这是我的密码: constructor(props){ super(props); projets = [ { "text":"ProjectName", "progress":"30", "budge

React native初学者在这里,我正在尝试制作一个应用程序,当我按下自定义组件时,它会运行一个函数,但当我尝试这样做时,我得到了“undefined不是一个对象(正在计算'\u this2.setProject.bind')”错误

这是我的密码:

constructor(props){

super(props);

projets = [
    {
        "text":"ProjectName",
        "progress":"30",
        "budget":"36000",
        "totalDays":"50",
        "design":"10",
        "integration":"12",
        "dev":"30"
    },

var progress = 0;
var totalDays = 54;
var budget = 24000;

this.state = {
  projets: projets,
  progress: progress,
  totalDays: totalDays,
  budget: budget
}

this.setProject = this.setProject.bind(this);

}


{this.state.projets.forEach(函数(projet,索引){
推(
{this.setProject.bind(this)}selected={false}key={index}projet.progress}budget={projet.budget}totalDays={parseInt(projet.design)+parseInt(projet.integration)+parseInt(projet.dev)text={projet.text}design={projet.design integration}integration={projet.dev
);
})}
{projectsArray}

您的代码有两个问题

首先:-您不需要用3种方式绑定函数,这会导致代码冗余。 因此,您可以调用
onPress={this.setProject}

Second:-您可以简单地使用
map
函数创建一个新的数组,并在该数组中的每个元素上调用提供的函数,而不是使用
forEach
,推送数组然后渲染它

所以你可以

   {this.state.projets.map((projet, index) => ( //... Use arrow function here to bind this parameter

     <ItemProjet key={index} onPress={this.setProject} selected={false}
       key={index} progress={projet.progress} budget={projet.budget}
       totalDays={parseInt(projet.design)+parseInt(projet.integration)+parseInt(projet.dev)}
       text={projet.text} design={projet.design} integration={projet.integration} dev={projet.dev}/>
    ))}
{this.state.projets.map((projet,index)=>(/…在此使用箭头函数绑定此参数
))}

您应该这样声明函数(自动绑定到类):

然后像这样使用它:

<ItemProjet onPress={this.setProject} //other props />

您可以使用ES6解决此特定用例

在您的情况下,您可以在组件中以以下方式声明
setProject()
函数:

    setProject = () => {
      console.log('test');
    };
在此之后,您只需键入以下内容即可调用该函数:


this.setProject()
onClick={this.setProject}

它可以工作!非常感谢你,花了一天时间想弄明白:)
setProject = () => {
  console.log("test");
}
<ItemProjet onPress={this.setProject} //other props />
    setProject = () => {
      console.log('test');
    };