猿问

通过类外函数(或替代方法)操纵状态

希望你过得愉快。考虑到我对 React 的了解程度,我可能会因为这个问题而稍微惹恼你。


这是设置:我的作品集网站有一个“项目”页面,我在其中展示了一个完整的项目,侧面有全尺寸图像和详细信息,在该页面下我有所有其他项目的列表。一旦点击其中之一,特色项目就会改变。我敢肯定,对大多数人来说这是一件非常简单的事情,但我似乎被卡住了。


这是我目前的设置方式:


组件类之外的一个名为“projects”的数组来存储它们,一个项目如下所示:

  {

    key: 0,

    title: "Project title",

    description:

      "Lorem ipsum",

    details: [

      "...",

      "...",

      "..."

    ].map((detail, i) => <li key={i}>{detail}</li>),

    image: ImageObject

  },

此函数(在类的 render 方法中引用)也在主要组件类之外,它为每个项目创建一个 div

function ProjectList(props) {

  const projects = props.projects;

  const projectItems = projects.map(project => (

    <div key={project.key}>

      <a href="#">

        <img src={project.image} alt={project.title} />

      </a>

    </div>

  ));


  return <div className="row">{projectItems}</div>;

}

而 render 方法中的引用是这样的:


<ProjectList projects={projects} />

现在我们进入 Projects 类,有一个名为“currentProjectIndex”的状态值和一个“setProject”函数:

setProject = index => {

   this.setState({ currentProjectIndex: index });

 };

一切正常并正确显示,如果我手动编辑状态,它确实会显示相关项目,但我不确定如何在此处进行。我已经尝试向 div 和 a 标签添加一个 onClick 属性,但似乎我无法在主类之外引用 setState,我认为这是有道理的,但是如果出现以下情况,则在渲染方法中无法识别 ProjectList 函数我把它放在主类中。


我意识到这可能是一些非常基本的东西,但我有一种感觉,我可能完全错误地处理了这个过程,而且我在这里完全走错了路。要么那样,要么我只是愚蠢,这两者都是完全可能的。无论哪种方式,我都非常感谢您的任何建议!


蝴蝶刀刀
浏览 109回答 1
1回答

ITMISS

你可以试试这个:添加一个按钮,点击事件调用 setProject 并传递索引(即 project.key,对吗?)作为参数。您可能还想添加一个 event.preventDefault。希望能帮助到你。这是代码:setProject = (event, index) => {&nbsp; &nbsp;event.preventDefault();&nbsp; &nbsp;this.setState({ currentProjectIndex: index });&nbsp;};function ProjectList(props) {&nbsp; const projects = props.projects;&nbsp; const projectItems = projects.map(project => (&nbsp; &nbsp; <div key={project.key}>&nbsp; &nbsp; &nbsp; <a href="#">&nbsp; &nbsp; &nbsp; &nbsp; <img src={project.image} alt={project.title} />&nbsp; &nbsp; &nbsp; </a>&nbsp; &nbsp; &nbsp; <button&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; type='button'&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; onClick={event => { this.setProject(event, project.key) }}&nbsp; &nbsp; &nbsp; >&nbsp; &nbsp; &nbsp; Select this project&nbsp; &nbsp; &nbsp; </button>&nbsp; &nbsp; </div>&nbsp; ));&nbsp; return <div className="row">{projectItems}</div>;}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答