Zah*_*aki 0 reactjs react-native react-navigation
我想在react-native header中添加按钮,该按钮是为了在页面中mas和unmask密码,当我改变状态以改变secureTextEntry值时点击的问题,图标不会改变将保留为初始值;该功能工作正常,但图标不能改变
this.state.secureTextEntry ? "eye" : "eye-slash"
Run Code Online (Sandbox Code Playgroud)
这是主要代码
class ChangePasswordScreen extends Component {
constructor(props) {
super(props);
this.state = {
newPassword: null,
currentPassword: null,
confirmPassword: null,
errors: [],
secureTextEntry: true
};
this.maskPassword = this.maskPassword.bind(this)
}
componentDidMount() {
this.props.navigation.setParams({
headerRight: ( < TouchableOpacity onPress = {
() => {
this.maskPassword();
}
} > < Icon style = {
styles.eyeIcon
}
name = {
this.state.secureTextEntry ? "eye" : "eye-slash"
}
size = {
20
}
color = {
Colors.WHITE
}
/></TouchableOpacity > )
})
}
static navigationOptions = ({
navigation
}) => {
return {
// headerTitle: <LogoTitle />,
headerRight: navigation.state.params && navigation.state.params.headerRight,
};
};
maskPassword = () => {
this.setState({
secureTextEntry: !this.state.secureTextEntry
})
}
Run Code Online (Sandbox Code Playgroud)
}
小智 5
问题是this.setState不会重新渲染 header 组件。如果您想正确更改标题,则必须再次调用setParams
在componentDidMount 中试试这个代码
componentDidMount() {
this.props.navigation.setParams({
headerRight: this.setHeaderRight(this.state.secureTextEntry)
});
}
Run Code Online (Sandbox Code Playgroud)
设置标题右侧的功能
setHeaderRight = state => {
//console.log("setHeaderRight", this.state.secureTextEntry);
return (
<TouchableOpacity
onPress={() => {
this.maskPassword();
}}
>
<Icon
style={styles.eyeIcon}
name={state ? "eye" : "eye-slash"}
size={20}
color={Colors.WHITE}
/>
</TouchableOpacity>
);
};
Run Code Online (Sandbox Code Playgroud)
状态设置时再次设置标题
maskPassword = () => {
this.setState({
secureTextEntry: !this.state.secureTextEntry
});
this.props.navigation.setParams({
headerRight: this.setHeaderRight(!this.state.secureTextEntry)
});
};
Run Code Online (Sandbox Code Playgroud)
有点晚了,不过可能会帮助某人。
如果您希望从屏幕本身而不是 App.js 文件向屏幕的标题添加按钮,并且您正在使用功能组件,则如下所示:
import { useNavigation } from '@react-navigation/native'
export default function () {
const nav = useNavigation();
useEffect(() => {
nav.setOptions({
headerRight: () => <Button />,
});
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13099 次 |
| 最近记录: |