我第一次使用 React,我有一个应用程序可以从用户那里获取两个号码并让他们选择一个操作员。我想获取该信息并将其显示在子组件中,但我可以终生获取它。
<script type="text/babel">
const main = ReactDOM.createRoot(document.getElementById('root'));
function Inputs(props) {
const[val1, setVal1] = React.useState(props.num1);
const[val2, setVal2] = React.useState(props.num2);
let symbols = ['+', '-', 'x', '÷'];
const[sym, setSym] = React.useState(props.opp);
const getVal = () => {
setVal1(first.value);
setVal2(second.value);
}
const getSym = (num) => {
setSym(symbols[num])
}
return(
<div>
<input id= 'first'></input>
<input id= 'second'></input>
<p>{val1}</p>
<p>{val2}</p>
<p>{sym}</p>
<button id= 'get' onClick ={getVal}>get</button>
<button id= 'add' onClick ={() => getSym(0)}>+</button>
<button id= 'subtract' onClick ={() => getSym(1)}>-</button>
<button id= 'multiply' onClick ={() => getSym(2)}>x</button>
<button id= 'divide' onClick ={() => getSym(3)}>÷</button>
<SubComponent />
</div>
)
}
class SubComponent extends React.Component {
render() {
return(
<p>SubComponent{this.props.value}</p>
)
}
}
main.render(<Inputs />);
我尝试过使用道具和其他一些东西,但没有骰子
我可以看到你在调用“SubComponent”时没有传递任何道具,但尝试像这样访问:
class SubComponent extends React.Component {
render() {
return(
<p>SubComponent{this.props.value}</p>
)
}
}
相反,您应该像一样将道具传递给“SubComponent
class SubComponent extends React.Component {
render() {
const { val1, val2, sym } = this.props.value;
return (
<div>
<p>Value 1: {val1}</p>
<p>Value 2: {val2}</p>
<p>Symbol: {sym}</p>
</div>
);
}
}