我有 ProductList
组件
import Title from "./Title";
class ProductList extends Component {
constructor(props) {
super(props);
this.state = {};
}
render() {
return <Title name="Our" title="Products" />;
}
}
和 Title
组件被导出,然后在 ProductList
组件中使用。
class Title extends Component {
constructor(title, name) {
super();
this.title = title;
this.name = name;
}
render() {
return (
<div className="product-title">
{this.name} <strong>{this.title}</strong>
</div>
);
}
}
但我无法呈现 title
和 name
。
此外,还有一个问题如果我将基于类的组件编写为基于函数的组件,我们需要这样做 function Title({ name, title })
为什么我们需要括号 {}把 name
和 title
包起来?
最佳答案
props
可在 this.props
中用于基于类的组件。这里不需要构造函数
class Title extends Component {
render() {
const {name, title } = this.props
return (
<div className="product-title">
{name} <strong>{title}</strong>
</div>
);
}
}
If i write that class based component to function based component we need to do it this way
function Title({ name, title })
why do we need brackets to wrap name and title there?
这是一个名为 destructuring assignment 的模式这使得将数组中的值或对象中的属性解压缩到不同的变量中成为可能
您可以传递一个对象
作为参数,并且只在函数体内或直接在声明中解构它
const user = {name: 'John', surname: 'Doe'}
logUser(user)
const logUser = user =>{
const { name, surname } = user
console.log(name, surname)
}
相当于
const logUser = ({ name, surname }) => console.log(name, user)
因为功能组件接收的唯一参数是props
,你可以像这样传递它
<Child foo='bar' />
并直接从props
对象中解构参数
const Child = ({ foo }) => <span> {foo} </span>
关于javascript - 将 Prop 传递给子组件的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58843222/