1. 程式人生 > >react 入門-建立元件(3)工廠方法

react 入門-建立元件(3)工廠方法

例項

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Factories</title>
</head>
<body>

<!-- Target Container -->
<div id="react-container"></div>

<!-- React Library & React DOM-->
<script src="https://unpkg.com/
[email protected]
/umd/react.development.js"
>
</script> <script src="https://unpkg.com/react-d[email protected]/umd/react-dom.development.js"></script> <script> const { render } = ReactDOM const foodList = ({ list }) => React.createElement('ul', null, list.map((item, i) => React.createElement('li'
, {key: i}, item) ) ) const listFactory = React.createFactory(foodList) const list = [ "1 apple", "1 banana", "2 oranges", "2 tomatos" ] render( listFactory({list}), document.getElementById('react-container') )
</script
>
</body> </html>

說明

1、建立無狀態函式

const foodList = ({ list }) =>
        React.createElement('ul', null,
            list.map((item, i) =>
                React.createElement('li', {key: i}, item)
            )
)

2、建立工廠方法

const listFactory = React.createFactory(foodList)

3、使用工廠方法,傳入實參

render(
    listFactory({list}),
    document.getElementById('react-container')
)