reactjs - 使用 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;
我将不胜感激任何指示!
非常感谢,
凯蒂
解决方案
问题在于您{type}
用来与“选择”进行比较的下面的行
if({type} ==='select')
它应该只是
if(type ==='select')
推荐阅读
- php - 具有相同键和值的数组的总和值
- python - 标点符号、停用词和带有 spacy 的词形还原
- php - 在 laravel 5.8 中注册期间添加 ROLE 时,参数 1 传递给 Illuminate\Auth\SessionGuard::login()
- c# - 我想在列表视图中制作标题并在 UWP 应用程序中的每个列表视图下添加项目。我该怎么做?
- c++ - 我可以在 c++17 代码中使用 c++11 开发的库吗?
- angular-test - 角度单元测试异步调用
- python - 如何根据单词匹配创建新列
- sqlite - 用 sqlite 连接 symfony
- javascript - 通过浏览器中的控制台使用 javascript 单击按钮
- image - Xamarin 从 pdf 文件中提取图像