*** props 부분 이해가 잘 안 된 채로 작성해서 다시 이해하고 정리할 예정이다...
<Button title="Button" />
src/components/MyButton.js
import React from "react"; // 리액트 호출
import { TouchableOpacity, Text } from "react-native"; // 리액트 네이티브에서 제공하는 컴포넌트 추가
const MyButton = props => {
console.log(props);
return (
<TouchableOpacity
style={{
backgroundColor: '#3498db',
padding: 16,
margin: 10,
borderRadius: 8,
}}
onPress={() => alert('Click!!!')}
>
<Text style={{ color: 'white', fontSize: 24}}>{props.title}</Text>
</TouchableOpacity>
);
};
export default MyButton;
src/App.js
import React from 'react';
import { Text, View } from 'react-native';
import MyButton from './components/MyButton';
const App = () => {
return (
<View
style={{
flex:1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
}}
>
<Text style={{ fontSize:30, marginBottom:10 }}>Props</Text>
<MyButton title="Button" />
</View>
);
}
export default App;
실행 결과
const MyButton = props => {
console.log(props);
return (
<TouchableOpacity
style={{
backgroundColor: '#3498db',
padding: 16,
margin: 10,
borderRadius: 8,
}}
onPress={() => alert('Click!!!')}
>
<Text style={{ color: 'white', fontSize: 24}}>{props.children || props.title}</Text>
</TouchableOpacity>
);
};
export default MyButton;
src/App.js
const App = () => {
return (
<View
style={{
flex:1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
}}
>
<Text style={{ fontSize:30, marginBottom:10 }}>Props</Text>
<MyButton title="Button" />
<MyButton title="Button">Children Props</MyButton>
</View>
);
}
export default App;
실행 결과
src/components/MyButton.js에 다음 코드를 추가해줌으로써 default prop을 지정해준다
MyButton.defaultProps = {
title: "Btn"
};
src/App.js
<MyButton title="Button" />
<MyButton title="Button">Children Props</MyButton>
<MyButton />
실행 결과
npm install prop-types
import PropTypes from 'prop-types';
const MyButton = props => {
console.log(props);
return (
<TouchableOpacity
style={{
backgroundColor: '#3498db',
padding: 16,
margin: 10,
borderRadius: 8,
}}
onPress={() => alert('Click!!!')}
>
<Text style={{ color: 'white', fontSize: 24}}>{props.children || props.title}</Text>
</TouchableOpacity>
);
};
MyButton.PropTypes = {
title: PropTypes.number,
}
MyButton.defaultProps = {
title: "Btn"
};
src/components/MyButton.js에 다음 코드를 추가한다
import PropTypes from 'prop-types';
MyButton.PropTypes = {
title: PropTypes.number,
}
MyButton.defaultProps = {
title: "Btn"
};
const [state, setState] = useState(initialState);