在之前的博客里,博主写了怎么在class component和JSX里使用props了,那么现在博主将演示怎么在functional component里用props. 还是在src文件夹下创建一个Testprops.js文件。
// Testprops.js文件
import React from 'react'
function testprops(props) {
console.log(props);
return (
<div>
<h1>
Hello {props.name}, friend's name {props.friendName}
</h1>
{props.children}
</div>
)
}
export default testprops;
在App.js文件里:
// App.js 文件
import React from 'react';
import './App.css';
import Testprops from './Testprops';
function App() {
return (
<div className="App">
<Testprops name="AAA" friendName="DDD">
<p>This is the first children</p>
</Testprops>
<Testprops name="BBB" friendName="EEE">
<button>Action</button>
</Testprops>
<Testprops name="CCC" friendName="FFF"/>
</div>
);
}
export default App;
结果如下:

还有没有其他方法来实现相同的效果呢?答案是有的
// Testprops.js文件
import React from 'react'
function testprops(props) {
const {name, friendName, children} = props
return (
<div>
<h1>
Hello {name}, friend's name {friendName}
</h1>
{children}
</div>
)
}
export default testprops;
在App.js 文件里,不需要修改什么
// App.js 文件
import React from 'react';
import './App.css';
import Testprops from './Testprops';
function App() {
return (
<div className="App">
<Testprops name="AAA" friendName="DDD">
<p>This is the first children</p>
</Testprops>
<Testprops name="BBB" friendName="EEE">
<button>Action</button>
</Testprops>
<Testprops name="CCC" friendName="FFF"/>
</div>
);
}
export default App;
结果跟上面的一样。
如果有哪里写的不对,就指出来吧!
或者是觉得写的好,就用点赞来取代五星好评吧!
本文详细介绍了如何在React的FunctionComponent中使用Props,通过具体示例展示了Props的传递和使用方法,包括Props的解构和默认Props的设置。
863

被折叠的 条评论
为什么被折叠?



