是否可以像下面的代码一样创建自定义模板并导出并重用?
import React from 'react'
import { View, Text } from 'react-native'
const CustomView = () => {
return (
<View>
<Text>Test 1 </Text>
*** custom code ***
</View>
)
}
export default CustomView
现在我如何使用上面的CustomView并添加我自己的标签,例如
import CustomView from "../CustomView";
return (
<CustomView>
<Text>Test 2 </Text>
</CustomView>
)
所以当我运行时,我的输出将是
Test 1
Test 2
我们能做这样的事吗?因此,我可以通过重用模板来更好地组织代码。
这样做是可能的,也是一种很好的做法。如果你想把其他组件放在你的自定义组件中,那么自定义组件将是父组件,里面的部分将是子组件。
自定义视图.js
import React from 'react'
import { View, Text } from 'react-native'
const CustomView = ({ children }) => {
return (
<View>
<Text>Test 1</Text>
{children}
</View>
)
}
export default CustomView;
App.js(或其他文件(
import React from "react";
import { Text } from "react-native";
const App = () => {
return (
<CustomView>
<Text>Test 2</Text>
</CustomView>
);
}
export default App;
当然,您需要设置自定义组件的样式。别忘了,最佳实践是始终创建尽可能多的可重用组件。更多的代码并不意味着更好的代码。
这里是另一个自定义或可重用组件的例子。
MyTextInput.js
import React from 'react';
import {
View,
Dimensions,
TextInput
} from 'react-native';
const { width, height } = Dimensions.get("window");
export default MyTextInput = ({placeholder, onChangeText, value, secureTextEntry, keyboardType}) => {
return (
<View style={inputContainerStyle}>
<TextInput
secureTextEntry={secureTextEntry}
style={inputStyle}
placeholder={placeholder}
onChangeText={onChangeText}
value={value}
placeholderTextColor="#9B9A9B"
underlineColorAndroid="transparent"
keyboardType={keyboardType}
/>
</View>
)
}
const inputContainerStyle = {
flexDirection: 'row',
width: width * 0.90,
height: height * 0.06,
borderBottomWidth: 0.5,
borderBottomColor: "#9B9A9B",
marginTop: height * 0.02,
paddingBottom: height * 0.02,
};
const inputStyle = {
flex: 1,
fontSize: 15,
color: "#9B9A9B",
};
App.js
import React from 'react';
import { View, StyleSheet } from 'react-native';
import MyTextInput from './MyTextInput';
export default function App() {
return (
<View style={{ marginTop: 50 }}>
<MyTextInput
placeholder="Password"
onChangeText={onPasswordChange}
value={password}
secureTextEntry={this.state.showPassword}
/>
</View>
);
};