首页 > 解决方案 > 使用 Reactjs 将道具传递给功能组件时,如果语句不起作用?

问题描述

我刚刚开始学习 React,我的功能组件中的 if 语句(在 下面显示的ChooseInputType.js中)正在返回“false”,即使我希望它返回“true”。我的简化代码如下 - 任何人都可以发现问题吗?如果相关的话,我想使用 Hooks 而不是 Classes!

表单.js

import React from 'react';
import ChooseInputType from './ChooseInputType';

function App(){
    return(
        <ChooseInputType 
            type="select"
        ></ChooseInputType >
);
}

选择InputType.js

function ChooseInputType({type}){
    if({type} ==='select'){
        return (<div>True: Type is {type} </div>);
    else{
        return (<div>False: Type is {type} </div>);
    }
}
export default ChooseInputType;

从上面的 Form.js 中可以看到,传递给 ChooseInputType 组件的 type 属性等于“select”,但返回的结果却错误地显示以下内容:

结果

False: Type is select

如果我在 ChooseInputType.js 中创建一个变量(如下所示),则不会发生这种情况,所以它一定与我将 type 属性传递给 ChooseInputType 组件的方式有关吗?

    function ChooseInputType({type}){
    //I have removed the props part by creating a type variable here
        const type="select";
        if(type ==='select'){
            return (<div>True</div>);
        else{
            return (<div>False</div>);
        }
    }
    export default ChooseInputType;

我将不胜感激任何指示!

非常感谢,

凯蒂

标签: reactjsif-statement

解决方案


问题在于您{type}用来与“选择”进行比较的下面的行

if({type} ==='select')

它应该只是

if(type ==='select')

推荐阅读