【问题标题】:Show corresponding div onclick dynamic components [REACT]显示对应的 div onclick 动态组件 [REACT]
【发布时间】:2022-09-28 02:33:03
【问题描述】:

我正在创建一个谜语游戏。问题首先在隐藏的 div 中显示解决方案。如何获得在特定谜语上单击的目标并仅在另一个 div 中显示该谜语的解决方案。

问题在一个对象中:

const stories = [
{ id: 1, title: first riddle, solution: this is the first solution }, 
{ id: 2, title: second riddle, solution: this is the second solution }];

我在 Card 组件中渲染了 stories 对象,并通过它们进行了映射:

{ stories.map((story, index) => 
<Story key={index} id={story.id} title={story.title} desc={story.desc} grade={story.grade} /> )}

我在 Card 组件上与onClick={this.handleClick} 一起尝试了一些东西,但我无法弄清楚如何展示解决方案。

    标签: javascript reactjs components


    【解决方案1】:

    所以,你有两个div。第一个 div 它的问题,第二个 div 它的解决方案。只有当我点击第一个 div 时,我才能显示第二个?

    如果我正确理解案例,您可以在 Story 组件中管理状态,当您单击第一个 div 时,您可以设置 setShowSolution(true)

    升级版:

    如果您使用功能组件:

    const Story () => {
       ...your code
       const [showSolution, setShowSolution] = useState(false);
    
       const clickHandler = () => {
           ...your code
           setShowSolution(true);
       };
    
       return (
         ...your code
    
         <div onClick={clickHandler}>{question}</div>
    
    
         {showSolution && (
            <div>{solution}</div>
         )}
    
         ...your code
       );
    }
    
    

    或课程

    example

    
    class Story extends Component {
      ...your code
      state = {
        showSolution: false
      };
    
       clickHandler = () => {
           ...your code
           this.setState({ showSolution: true });
       };
    
       render() {
          return (
             ...your code
    
             <div onClick={this.clickHandler}>{question}</div>
    
    
             {this.state.showSolution && (
               <div>{solution}</div>
             )}
    
             ...your code
           );
       }
    
    }
    
    

    【讨论】:

    • 是的,但因此我的问题是,我该怎么做?我对 REACT 真的很陌生,我看了很多视频,但无法弄清楚。
    • 你使用了功能组件或类?
    • 我用过类
    • 我更新了示例
    • 我收到一条错误消息,提示 setState 未定义
    【解决方案2】:
    { stories.map((story, index) => <Story key={index} id={story.id} title={story.title} desc={story.desc} grade={story.grade} onClick={() => console.log(story.id)} /> )}
    

    OnClick 事件将控制每个对象的唯一标识符。

    【讨论】:

    • 即使没有点击 div,这也会记录 id?
    • @Sbaliyev 改用它,它将在单击组件事件 onClick={() => console.log(story.id)} 时起作用
    猜你喜欢
    • 2020-12-10
    • 2017-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-23
    • 2020-04-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多