在之前的博客裏,博主寫了怎麼在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;
結果跟上面的一樣。
如果有哪裏寫的不對,就指出來吧!
或者是覺得寫的好,就用點贊來取代五星好評吧!