React에서 자녀의 상태에 액세스하는 방법?
나는 다음과 같은 구조를 가지고 있습니다 :
FormEditor
-여러 FieldEditor를 보유 FieldEditor
-양식의 필드를 편집하고 상태에 대한 다양한 값을 저장합니다.
FormEditor 내에서 단추를 클릭하면 모든 FieldEditor
구성 요소 에서 필드에 대한 정보 , 해당 상태 에있는 정보를 수집하여 FormEditor 내에 모두 포함시킬 수 있기를 원합니다.
나는 FieldEditor
상태 외부의 필드에 대한 정보를 저장하는 FormEditor
대신에 상태를 저장하는 것을 고려 했습니다 . 그러나 정보를 변경하고 상태로 저장 FormEditor
하면 각 FieldEditor
구성 요소 를 청취 해야 합니다 .
대신 어린이의 상태에 접근 할 수 없습니까? 이상적입니까?
개별 FieldEditors에 대한 onChange 핸들러가 이미있는 경우 상태를 FormEditor 구성 요소로 옮기고 콜백을 거기에서 상위 상태를 업데이트하는 FieldEditors로 전달하는 이유를 알 수 없습니다. 그것은 더 반응적인 방법으로 보입니다.
아마도 이것의 라인을 따라 뭔가 :
class FieldEditor extends React.Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
const text = event.target.value;
this.props.onChange(this.props.id, text);
}
render() {
return (
<div className="field-editor">
<input onChange={this.handleChange} value={this.props.value} />
</div>
);
}
}
class FormEditor extends React.Component {
constructor(props) {
super(props);
this.state = {};
this.handleFieldChange = this.handleFieldChange.bind(this);
}
handleFieldChange(fieldId, value) {
this.setState({ [fieldId]: value });
}
render() {
const fields = this.props.fields.map(field => (
<FieldEditor
key={field}
id={field}
onChange={this.handleFieldChange}
value={this.state[field]}
/>
));
return (
<div>
{fields}
<div>{JSON.stringify(this.state)}</div>
</div>
);
}
}
// Convert to class component and add ability to dynamically add/remove fields by having it in state
const App = () => {
const fields = ["field1", "field2", "anotherField"];
return <FormEditor fields={fields} />;
};
ReactDOM.render(<App />, document.body);
http://jsbin.com/qeyoxobixa/edit?js,output
편집 : 단지 그것을 위해 관심있는 사람을 위해 후크를 사용하여 위 예제를 다시 작성했습니다.
const FieldEditor = ({ value, onChange, id }) => {
const handleChange = event => {
const text = event.target.value;
onChange(id, text);
};
return (
<div className="field-editor">
<input onChange={handleChange} value={value} />
</div>
);
};
const FormEditor = props => {
const [values, setValues] = useState({});
const handleFieldChange = (fieldId, value) => {
setValues({ ...values, [fieldId]: value });
};
const fields = props.fields.map(field => (
<FieldEditor
key={field}
id={field}
onChange={handleFieldChange}
value={values[field]}
/>
));
return (
<div>
{fields}
<pre>{JSON.stringify(values, null, 2)}</pre>
</div>
);
};
// To add abillity to dynamically add/remove fields keep the list in state
const App = () => {
const fields = ["field1", "field2", "anotherField"];
return <FormEditor fields={fields} />;
};
하위 구성 요소의 상태에 액세스하는 방법에 대해 자세히 알아보기 전에이 특정 시나리오를 처리하는 더 나은 솔루션에 대한 Markus-ipse 의 답변 을 읽으십시오 .
If you do indeed wish to access the state of a component's children, you can assign a property called ref
to each child. There are now two ways to implement references: Using React.createRef()
and callback refs.
Using React.createRef()
This is currently the recommended way to use references as of React 16.3 (See the docs for more info). If you're using an earlier version then see below regarding callback references.
You'll need to create a new reference in the constructor of your parent component and then assign it to a child via the ref
attribute.
class FormEditor extends React.Component {
constructor(props) {
super(props);
this.FieldEditor1 = React.createRef();
}
render() {
return <FieldEditor ref={this.FieldEditor1} />;
}
}
In order to access this kind of ref, you'll need to use:
const currentFieldEditor1 = this.FieldEditor1.current;
This will return an instance of the mounted component so you can then use currentFieldEditor1.state
to access the state.
Just a quick note to say that if you use these references on a DOM node instead of a component (e.g. <div ref={this.divRef} />
) then this.divRef.current
will return the underlying DOM element instead of a component instance.
Callback Refs
This property takes a callback function that is passed a reference to the attached component. This callback is executed immediately after the component is mounted or unmounted.
For example:
<FieldEditor
ref={(fieldEditor1) => {this.fieldEditor1 = fieldEditor1;}
{...props}
/>
In these examples the reference is stored on the parent component. To call this component in your code, you can use:
this.fieldEditor1
and then use this.fieldEditor1.state
to get the state.
One thing to note, make sure your child component has rendered before you try to access it ^_^
As above, if you use these references on a DOM node instead of a component (e.g. <div ref={(divRef) => {this.myDiv = divRef;}} />
) then this.divRef
will return the underlying DOM element instead of a component instance.
Further Information
If you want to read more about React's ref property, check out this page from Facebook.
Make sure you read the "Don't Overuse Refs" section that says that you shouldn't use the child's state
to "make things happen".
Hope this helps ^_^
Edit: Added React.createRef()
method for creating refs. Removed ES5 code.
Now You can access the InputField's state which is the child of FormEditor .
Basically whenever there is a change in the state of the input field(child) we are getting the value from the event object and then passing this value to the Parent where in the state in the Parent is set.
On button click we are just printing the state of the Input fields.
The key point here is that we are using the props to get the Input Field's id/value and also to call the functions which are set as attributes on the Input Field while we generate the reusable child Input fields.
class InputField extends React.Component{
handleChange = (event)=> {
const val = event.target.value;
this.props.onChange(this.props.id , val);
}
render() {
return(
<div>
<input type="text" onChange={this.handleChange} value={this.props.value}/>
<br/><br/>
</div>
);
}
}
class FormEditorParent extends React.Component {
state = {};
handleFieldChange = (inputFieldId , inputFieldValue) => {
this.setState({[inputFieldId]:inputFieldValue});
}
//on Button click simply get the state of the input field
handleClick = ()=>{
console.log(JSON.stringify(this.state));
}
render() {
const fields = this.props.fields.map(field => (
<InputField
key={field}
id={field}
onChange={this.handleFieldChange}
value={this.state[field]}
/>
));
return (
<div>
<div>
<button onClick={this.handleClick}>Click Me</button>
</div>
<div>
{fields}
</div>
</div>
);
}
}
const App = () => {
const fields = ["field1", "field2", "anotherField"];
return <FormEditorParent fields={fields} />;
};
ReactDOM.render(<App/>, mountNode);
참고URL : https://stackoverflow.com/questions/27864951/how-to-access-childs-state-in-react
'Programming' 카테고리의 다른 글
SQLite 데이터베이스 파일에 가장 적합한 확장자는 무엇입니까? (0) | 2020.05.13 |
---|---|
Java에서 언제 varargs를 사용합니까? (0) | 2020.05.13 |
IDE를 설치하지 않고 빌드 서버에 VS2017 버전의 msbuild를 어떻게 설치할 수 있습니까? (0) | 2020.05.13 |
N-Tier 아키텍처 란 무엇입니까? (0) | 2020.05.13 |
Android-패키지 이름 규칙 (0) | 2020.05.13 |