我正在尝试将值"red"
从index.js
传递到box.js
,但仍无法正常工作。基本上,我有一个定义box属性的组件,我想将背景颜色“红色”从index.js
传递到Box.js
组件。
// Box.js
import React from "react";
const box = {
// here i would like to get the vlue name assign it to background
background: this.props.name,
width: "250px",
height: "250px"
// more code that defines how the box looks like here
};
export default Box;
/// index.js
import React, { Component } from "react";
import { render } from "react-dom";
import Box from "./Box";
render() {
return (
// when calling Box, I would like to pass the value red to varivable name as shown below
<Box name="red"></Box>
)
}
我想念什么?
答案 0 :(得分:1)
您需要创建一个适当的组件:
// 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
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"/>)
}
});
答案 1 :(得分:0)
这个问题有些混乱,请帮助我们详细了解您的问题。
请注意,如果您不使用基于类的组件或构造函数,而不能使用“ props”,则不能使用“ this.props”
尝试如下更改Box组件:
const Box = (props) => {
return <p style={{background: props.name}}> Content </p>
}