尝试使用ReactJS和Redux创建一个简单的计算器。在其下方添加了一个输入框和一些按钮(对于数字0-9),以便在单击按钮时,使用按钮值更新输入框值。单击等于(=)按钮时,应评估输入字符串,并使用结果值更新输入框。无法弄清楚如何将按钮点击数据发送到输入框。以下是代码:
容器:
import React from 'react';
import Calculator from '../components/Calculator'
import {connect} from 'react-redux'
import store from '../store'
class CalcLogic extends React.Component{
render(){
return(
<div>
<div className="row" > Calculator </div> <br/>
<div className="row text-center" >
<input type="text" readonly="readonly" value={this.props.value} />
</div> <br/>
<div className="col-md-3 col-md-offset-4" style={{backgroundColor:'lightGrey' }} >
<div className="row ">
{
this.props.btns.map((item,key) =>{
return <Calculator key={key} item={item} value={this.props.value} />
})
}
</div>
</div>
</div>
);
}
}
function mapStateToProps (state) {
return{
value: state.value,
btns: state.btns
}
}
export default connect(mapStateToProps)(CalcLogic);
组件:
import React from 'react';
import {connect} from 'react-redux'
import {bindActionsCreator, bindActionCreators} from 'redux'
import {addElem,clear,equals} from '../actions/actions'
const Calculator=(props) => {
return(
<div className="container text-center" > <br/>
{
props.item == "clear"? <button className="btn btn-small btn-default col-md-3" key={props.key}
onClick={()=> {this.props.clear}} > {props.item} </button> : props.item == "="?<button className="btn btn-small btn-default col-md-3" key={props.key}
onClick={()=> {this.props.equals(props.value)}} > {props.item} </button>:<button className="btn btn-small btn-default col-md-3" key={props.key}
onClick={()=> {this.props.addElem(props.item)}} > {props.item} </button>
}
</div>
);
};
const mapDispatchToProps = (dispatch) => {
return{
addElem: (text) =>{
dispatch(addElem(text));
},
clear: () =>{
dispatch(clear());
} ,
equals: (value) =>{
dispatch(equals(value));
}
};
};
export default connect(() => {return {}; } , mapDispatchToProps)(Calculator);
减速器:
const calcState = {
value: 0,
btns: [ "clear", "=", "0", "/", "7", "8", "9", "*", "4", "5", "6", "+", "1", "2", "3", "-"]
}
const Reducer= (state = calcState,
action) => {
switch(action.type){
case 'ADDELEM':
return{
...state,
value: state.value == '0' ? action.payload : state.value + action.payload
}
case 'CLEAR':
return{
...state,
value:0
}
case 'EQUALS':
return{
...state,
value:eval(action.payload)
}
default: return state;
}
}
export default Reducer;
行动:
const addElem=(text)=> {
return{
type:'ADDELEM',
payload:text
};
},
clear=()=>{
return{
type:'CLEAR'
};
},
equals=(value)=> {
return{
type:'EQUALS',
payload:value
};
}
export {addElem,clear,equals};