Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/facebook/9.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
Reactjs 将道具从一个组件传递到另一个组件_Reactjs - Fatal编程技术网

Reactjs 将道具从一个组件传递到另一个组件

Reactjs 将道具从一个组件传递到另一个组件,reactjs,Reactjs,我正在尝试将值“red”从index.js传递到box.js,但尚未工作。基本上,我有一个定义box属性的组件,我想将背景颜色“红色”从index.js传递到box.js组件 //Box.js 从“React”导入React; 常数框={ //在这里,我想得到的vlue名称分配给背景 背景:this.props.name, 宽度:“250px”, 高度:“250px” //更多代码定义了框的外观 }; 导出默认框问题中有些混乱,请帮助我们详细了解您的问题 您的默认导出名称为“card”,您正

我正在尝试将值
“red”
index.js
传递到
box.js
,但尚未工作。基本上,我有一个定义box属性的组件,我想将背景颜色“红色”从
index.js
传递到
box.js
组件

//Box.js
从“React”导入React;
常数框={
//在这里,我想得到的vlue名称分配给背景
背景:this.props.name,
宽度:“250px”,
高度:“250px”
//更多代码定义了框的外观
};

导出默认框问题中有些混乱,请帮助我们详细了解您的问题

  • 您的默认导出名称为“card”,您正在尝试导入 “盒子”
  • 你所说的主要源代码是什么意思
  • 您的index.js没有正确的组件语法
请注意,如果您不是使用基于类的组件或构造函数,而是使用“props”,则不能使用“this.props”

尝试按以下方式更改长方体组件:

const Box = (props) => {
    return <p style={{background: props.name}}> Content </p>
}
const-Box=(道具)=>{
return

Content

}
您需要创建一个合适的组件:

// box.js
import React from "react";
const Box = (props) => {
  // here i would like to get the value name assign it to background
  const background = props.name;
  const width = "250px";
  const height = "250px";
  // more code that defines how the box looks like here
  return (
    // jsx code goes here
  );
};

export default Box;
在第二个代码段中,您没有正确使用它

// index.js
import React from "react";
import Box from "./box"; // assuming that the file name is box.js and it is in the same folder

const BoxDisplay = (props) => {
    return (
       <Box name="red"/>
    );
};

export default BoxDisplay;
//index.js
从“React”导入React;
从“/Box”/”导入框假设文件名为box.js且位于同一文件夹中
const-BoxDisplay=(道具)=>{
返回(
);
};
导出默认框显示;
或者,如果您想要实际的组件:

// index.js
import React, {Component} from "react";
import Box from "./box";

export default class BoxDisplay extends Component({
    constructor(props) {
        super(props)
        this.state = { //any initial state you want}
    }
    render() {
        return (<Box name="red"/>)
    }
});
//index.js
从“React”导入React,{Component};
从“/Box”导入框;
导出默认类BoxDisplay扩展组件({
建造师(道具){
超级(道具)
this.state={//您想要的任何初始状态}
}
render(){
返回()
}
});

我不确定我是否理解这个问题,但通常情况下,您可以通过
道具将值传递给组件。
编写的问题不清楚-您能否清理代码片段以显示您实际尝试的内容?现在大部分代码都是无效的JS。您的问题是将值从一个组件传递到另一个组件吗?正确的,我想将值red从主源代码传递到box,这样red将被指定为background colorbox.JS,index.JS不能位于同一个文件中,因为box.JS有两个原因。如果删除box.js,依赖于调用box.js的部分代码将失败。第二个问题是,我必须在我需要的任何地方重写相同的代码,这使得项目不合理地冗余。这是两个不同的文件-虽然如果你真的想合并它们-但我建议每个组件一个文件不确定重写代码的意思-你只需要在需要的地方导入box.js信息技术代码重用的精妙之处明白了吗?但由于某种原因,当我运行它时,它失败了。你能更具体一点吗?什么失败了?