티스토리 뷰
728x90
SMALL
const MyComponent = ({ name, favoriteNumber, children }) => {
children은 여기서 리액트 <MyComponent name="React" favoriteNumber={1}>리액트 </MyComponent>
props가 없을때 defaul
MyComponent.defaultProps = {
name: "기본 이름",
};
yarn add prop-types
타입확인 isRequired 쓰면 prop이 제공되지 않을때 경고
MyComponent.propTypes = {
name: propTypes.string,
favoriteNumber: propTypes.number.isRequired,
};
이벤트
import React, { useState } from "react";
const EventPractice = () => {
const [form, setForm] = useState({
username: "",
message: "",
});
const { username, message } = form;
const onChange = (e) => {
// setTimeout(() => console.log(e), 500);
const nextForm = {
...form, // 기존의 form 내용을 이 자리에 복사 한 뒤
[e.target.name]: e.target.value, // 원하는 값을 덮어씌우기
};
setForm(nextForm);
};
const onClick = () => {
alert(username + ": " + message);
setForm({
username: "",
message: "",
});
};
const onKeyPress = (e) => {
if (e.key === "Enter") {
onClick();
}
};
return (
<div>
<h1>이벤트 연습</h1>
<input
type="text"
name="username"
placeholder="유저명"
value={username}
onChange={onChange}
/>
<input
type="text"
name="message"
placeholder="아무거나 입력해보세요"
value={message}
onChange={onChange}
onKeyPress={onKeyPress}
/>
<button onClick={onClick}>확인</button>
</div>
);
};
export default EventPractice;
crud u빼고
import React, { useState } from "react";
const IterationSample = () => {
const [names, setNames] = useState([
{ id: 1, text: "눈사람" },
{ id: 2, text: "얼음" },
{ id: 3, text: "눈" },
{ id: 4, text: "바람" },
]);
const [inputText, setInputText] = useState("");
const [nextId, setNextId] = useState(5);
const onChange = (e) => setInputText(e.target.value);
const onClick = () => {
const nextNames = names.concat({
id: nextId,
text: inputText,
});
setNextId(nextId + 1);
setNames(nextNames);
setInputText("");
};
const onRemove = (id) => {
const nextNames = names.filter((name) => name.id !== id);
setNames(nextNames);
};
const nameList = names.map((name) => (
<li key={name.id} onDoubleClick={() => onRemove(name.id)}>
{name.text}
</li>
));
return (
<>
<input value={inputText} onChange={onChange} />
<button onClick={onClick}>추가</button>
<ul>{nameList}</ul>
</>
);
};
export default IterationSample;
에러발생
import React, { Component } from "react";
class ErrorBoundary extends Component {
state = { error: false };
componentDidCatch(error, info) {
this.setState({
error: true,
});
console.log({ error, info });
}
render() {
if (this.state.error) return <div>에러가 발생했습니다!</div>;
return this.props.children;
}
}
export default ErrorBoundary;
app
<ErrorBoundary>
<LifeCycleSample color={this.state.color} />
</ErrorBoundary>
생명주기
import React, { Component } from "react";
class LifeCycleSample extends Component {
state = { number: 0, color: null };
myRef = null;
constructor(props) {
super(props);
console.log("constructor");
}
static getDerivedStateFromProps(nextProps, prevState) {
console.log("getDerivedStateFromProps");
if (nextProps.color !== prevState.color) {
return { color: nextProps.color };
}
return null;
}
componentDidMount() {
console.log("componentDidMount");
}
shouldComponentUpdate(nextProps, nextState) {
console.log("shouldComponentUpdate", nextProps, nextState);
return nextState.number % 10 !== 4;
}
componentWillUnmount() {
console.log("componentWillUnmount");
}
handleClick = () => {
this.setState({
number: this.state.number + 1,
});
};
getSnapshotBeforeUpdate(prevProps, preState) {
console.log("getSnapshotBeforeUpdate");
if (prevProps.color !== this.props.color) {
return this.myRef.style.color;
}
return null;
}
componentDidUpdate(preProps, prevState, snapshot) {
console.log("componentDidUpdate", preProps, prevState);
if (snapshot) {
console.log("업데이트되기 직전 색상: ", snapshot);
}
}
render() {
console.log("render");
const style = { color: this.props.color };
return (
<div>
{this.props.missing.value}
<h1 style={style} ref={(ref) => (this.myRef = ref)}>
{this.state.number}
</h1>
<p>color: {this.state.color}</p>
<button onClick={this.handleClick}>더하기</button>
</div>
);
}
}
export default LifeCycleSample;
728x90
LIST
'책 > 리다기' 카테고리의 다른 글
리다기 정리6(뉴스뷰어 만들기) (0) | 2021.01.22 |
---|---|
리다기 정리5(immer, SPA) (0) | 2021.01.22 |
리다기 정리4(아이콘, 최적화) (0) | 2021.01.21 |
리다기 정리3(css) (0) | 2021.01.20 |
리다기 정리2(hook) (0) | 2021.01.19 |
댓글
공지사항