export class Register extends Component {
render() {
const [selectedGoal, setSelectedGoal] = React.useState(1);
return (
<RadioButtonRN
boxStyle={{
height: hp("6%"),
width: wp("80%"),
}}
activeColor="white"
boxActiveBgColor="red"
textColor="black"
textStyle={{ fontWeight: "bold" }}
data={goal}
initial={selectedGoal}
selectedBtn={(e) => setSelectedGoal(e.id)}
/>
{selectedGoal == 1 ? (
<View style={{ alignItems: "center" }}>
<Text style={{ color: "red", fontSize: 15, top: hp("5%") }}>
How much would you like to gain per week?
</Text>
<RadioButtonRN
style={{ top: hp("10%") }}
boxStyle={{
height: hp("6%"),
width: wp("80%"),
}}
activeColor="white"
boxActiveBgColor="red"
textColor="black"
textStyle={{ fontWeight: "bold" }}
data={details}
selectedBtn={(e) => console.log(e)}
/>
</View>
) : selectedGoal == 2 ? (
<View>
<Text>Ciao</Text>
</View>
) : (
<View>
<Text> you made it</Text>
</View>
)})}
大家好,我是编程新手,我尝试在 render() 下使用 const 然后在 RadioButtonRN 中使用它,但当然,它给了我一个无效的挂钩调用,我如何将其转换为在我的班级?
答案 0 :(得分:1)
我可以看到 2 个问题
1- 当组件返回多个元素时应使用片段例如使用
或
<>>
在以下链接中阅读更多内容:
https://reactjs.org/docs/fragments.html
2- 只能在功能组件上使用 react hook!
将您的代码更改为:
import React from "react";
export const Register = () => {
const [selectedGoal, setSelectedGoal] = React.useState(1);
return (
<>
<RadioButtonRN
boxStyle={{
height: hp("6%"),
width: wp("80%"),
}}
activeColor="white"
boxActiveBgColor="red"
textColor="black"
textStyle={{ fontWeight: "bold" }}
data={goal}
initial={selectedGoal}
selectedBtn={(e) => setSelectedGoal(e.id)}
/>
{selectedGoal == 1 ? (
<View style={{ alignItems: "center" }}>
<Text style={{ color: "red", fontSize: 15, top: hp("5%") }}>
How much would you like to gain per week?
</Text>
<RadioButtonRN
style={{ top: hp("10%") }}
boxStyle={{
height: hp("6%"),
width: wp("80%"),
}}
activeColor="white"
boxActiveBgColor="red"
textColor="black"
textStyle={{ fontWeight: "bold" }}
data={details}
selectedBtn={(e) => console.log(e)}
/>
</View>
) : selectedGoal == 2 ? (
<View>
<Text>Ciao</Text>
</View>
) : (
<View>
<Text> you made it</Text>
</View>
)}
</>
);
};
答案 1 :(得分:0)
您正在使用带有反应钩子的 class
组件。钩子仅适用于功能组件,但在这里您使用的是类。您可以在文档中阅读有关它的更多信息。
功能组件示例
export default function Register() {
const [selectedGoal, setSelectedGoal] = React.useState(1);
return <div>{selectedGoal</div>
}
答案 2 :(得分:0)
不要将 hooks
与 React 类一起使用。如果您使用类构建您的组件,则使用 state
。挂钩旨在用于 stateless
组件。
看这里: https://www.w3schools.com/react/react_state.asp
反应类状态:
class Someclass extends React.Component {
constructor() {
this.state = {
state_one: 1,
state_two: 'asd'
};
}
render() {
return (
<div>
{this.state.state_one} // <- usage
</div>
);
}
}
请注意,您可以像这样更改 this.state.some_state
:
this.setState({some_state: 'new_state'})
// or with using previous state:
this.setState({some_state: this.state.some_state + 1})
!!!在{}
this.setState()