我遇到以下错误,如果有人可以向我指出正确的方向,我会很乐意:) 我尝试了不同的方法,但是没有用。
编译失败 ./src/App.jsx 尝试导入错误:“ eval”未从“ mathjs”(导入为“ math”)中导出。
import React, { Component } from 'react';
import './App.css';
import { Button } from './components/Button';
import { Input } from './components/Input';
import { ClearButton } from './components/ClearButton';
import * as math from 'mathjs';
class App extends Component {
constructor(props) {
super(props);
this.state = {
input: ""
};
}
addToInput = val => {
this.setState({input: this.state.input + val});
}
handleEqual = () => {
this.setState({input: math.eval(this.state.input)});
}
render() {
return (
<div className="app">
<div className="calc-wrapper">
<Input input={this.state.input}></Input>
<div className="row">
<Button handleClick={this.addToInput}>7</Button>
<Button handleClick={this.addToInput}>8</Button>
<Button handleClick={this.addToInput}>9</Button>
<Button handleClick={this.addToInput}>/</Button>
</div>
<div className="row">
<Button handleClick={this.addToInput}>4</Button>
<Button handleClick={this.addToInput}>5</Button>
<Button handleClick={this.addToInput}>6</Button>
<Button handleClick={this.addToInput}>X</Button>
</div>
<div className="row">
<Button handleClick={this.addToInput}>1</Button>
<Button handleClick={this.addToInput}>2</Button>
<Button handleClick={this.addToInput}>3</Button>
<Button handleClick={this.addToInput}>+</Button>
</div>
<div className="row">
<Button handleClick={this.addToInput}>.</Button>
<Button handleClick={this.addToInput}>0</Button>
<Button handleClick={() => this.handleEqual()}>=</Button>
<Button handleClick={this.addToInput}>-</Button>
</div>
<div className="row">
<ClearButton handleClear={ () => this.setState({input: "" })}>Clear</ClearButton>
</div>
</div>
</div>
);
}
}
export default App;
答案 0 :(得分:1)
我遇到了同样的问题,我解决了如下:
我进行了更改:
handleEqual = () => {
this.setState({ input: math.eval(this.state.input) });
};
将 eval
更改为 evaluate
handleEqual = () => {
this.setState({ input: math.evaluate(this.state.input) });
};
现在完美运行。希望对你有帮助
答案 1 :(得分:0)
尝试将导入作为默认导入,然后使用它
import { evaluate } from 'mathjs';
console.log(evaluate('2 + 2'));
答案 2 :(得分:0)
导入为评估
import * as math from 'mathjs';
console.log(math.evaluate('2 + 3'))
// Or
import {evaluate } from 'mathjs';
console.log(evaluate('2 + 3'))
答案 3 :(得分:0)
我遇到了完全相同的问题,像您一样,我做了很多努力来解决它,但都失败了。我最终解决的方式如下: 首先,请确保您已使用以下命令从命令行下载了mathjs:npm install mathjs;并且在您的反应代码的顶部,放置以下语句:import * as from'mathjs'of math; (我可以从您的代码中看到后者)。
现在至关重要的第二步是,与其使用math.eval(expr)或math.evaluate(expr)来评估表达式,不如下面的示例,使用parse并结合评估进行编译:
const node1= math.parse('2 + 3');
const code1= node1.compile();
code1.evaluate(); // 5
这是我经过同样的错误和方法经过多次失败的尝试后终于尝试的方法,但它确实有效。这是mathjs库中列出的评估表达式的另一种方法。我知道距问这个问题已经有几个月了,但是这种解决方案将来仍然可以帮助某个人。
答案 4 :(得分:0)
使用 math.evaluate() 而不是 math.eval()。