gpt4 book ai didi

javascript - 如何更新 parent 的状态?

转载 作者:行者123 更新时间:2023-11-30 08:26:33 24 4
gpt4 key购买 nike

我刚开始使用react并尝试更新 parent 的状态,但到目前为止运气不好。

组件

class InputBox extends Component {
constructor(props) {
super(props);
this.type = props.type;
}
render() {
return (
<div>
<input type={this.type}/>
</div>
);
}
}

我想使用这个组件来切换密码的其他容器

constructor(props) {
super(props);
this.state = {
type: 'password',
wording: 'Show',
};
this.changeState = this.changeState.bind(this);
}

changeState() {
const oldState = this.state.type;
const isTextOrHide = (oldState === 'password');
const newState = (isTextOrHide) ? 'text' : 'password';
const newWord = (isTextOrHide) ? 'Hide' : 'Show';
this.setState({
type: newState,
label: newWord,
});
}

<Wrapper>
<InputBox type={this.state.type} />
<Toggle onClick={this.changeState}>{this.state.wording}</Toggle>
</Wrapper>

最佳答案

你可以这样做:

一、父组件:

import React, { Component } from 'react';
import { InputBox} from './InputBox'

class componentName extends Component {
state = {
password: '',
type: 'password',
wording: 'Show',
}

handleShow = (word) => {
this.setState({ wording: word })
}

handleChange = (e) => {
if(!this.state.password){
handleShow('Show')
} else {
handleShow('Hide')
}
this.setState({ password: e.target.value })
}

render() {
return (
<div>
<Wrapper>
<InputBox
name='password'
handleChange={this.handleChange}
password={this.state.password}
type={this.state.type} /> .
<Toggle onClick={this.changeState}>{this.state.wording}
</Toggle>
</Wrapper>
</div>
);
}
}

现在子组件:

import React from 'react';

export const InputBox = (props) => (
<input onChange={props.handleChange} value={props.password} type={props.type}/>
)
  1. state需要一直保留在parent中,然后通过props向下传递
  2. 子组件通常是无状态的,这意味着它们不需要是一个(可以只是一个返回jsx 的函数)和最重要的, 不能有state(state只在类组件中可用)

始终将状态传递给子组件因为无论 state 有多远,通过 props 它总是会改变源,在本例中是父级,国家的创造者

另一件重要的事情:

如果您使用 ES6 箭头函数,则不需要 constructor 来绑定(bind)您的函数。

像这样:handleSomething = () => { return ... }

另一件事:

你不需要constructor来设置state,你可以简单地做

state = { } 

它自动成为上下文的一部分 this

以这种方式思考你永远不会失败。

希望对你有帮助:)

关于javascript - 如何更新 parent 的状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44661549/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com