React Native父元件呼叫子元件
阿新 • • 發佈:2018-12-24
////用元件化寫的 import React, { Component } from "react"; import { Text, View } from "react-native"; import Greeting1 from "./Greeting.js"; class Greeting extends Component { render() { let { foo, bar } = { foo: "aaa", bar: "bbb" }; console.log(foo); console.warn(this.props.name) console.log(' this is a big date') return ( <View style={{alignItems: 'center'}}> <Text>Hello {this.props.name}!</Text> </View> ); } } export default class App extends Component { _log(log){ console.warn(log); return null; } render() { console.warn("main begin"); return ( <View style={{ alignItems: "center" }}> <Greeting name="Rexxar" /> <Greeting1 name="Jaina" /> <Greeting name="Valeera" /> {this._log("0000")} </View> ); } }
// Greeting.js 檔案 import React, { Component } from 'react'; import { Text, View } from 'react-native'; import PropTypes from 'prop-types' export default class Greeting extends React.Component { render() { console.warn(this.props.name); return ( <View style={{alignItems: 'center'}}> <Text>Hello {this.props.name}!</Text> </View> ); } }
上面的Demo 就是父元件呼叫子元件,如果不用元件形式寫,放在一個檔案裡,程式碼如下所示:
//不用元件化的形式寫的 //app.js 檔案裡 import React, { Component } from 'react'; import { Text, View } from 'react-native'; //元件化形式是這麼寫 class Greeting extends Component { render() { return ( <View style={{alignItems: 'center'}}> <Text>Hello {this.props.name}!</Text> </View> ); } } export default class LotsOfGreetings extends Component { _renderCellView(name){ return ( <View style={{alignItems: 'center'}}> <Text>Hello {name}!</Text> </View> ); } render() { return ( <View style={{alignItems: 'center'}}> {this._renderCellView("RXjava")} {this._renderCellView("RNIOS")} {this._renderCellView("RNandroid")} </View> ); } }