我有一个字符串,txt单击按钮时需要将其下载到文件中。如何使用React来实现呢?
txt
这是一个工作示例。在输入字段中输入文本,然后单击Download txt,这将下载txt包含您在输入中输入的内容的。
Download txt
此解决方案创建了一个新的MIME类型的 Blob对象 ,text并将其附加到href临时anchor(<a>)元素的,然后以编程方式触发该元素。
text
href
<a>
Blob对象代表不可变的原始数据的类似文件的对象。Blob表示的数据不一定是JavaScript原生格式。
class MyApp extends React.Component { downloadTxtFile = () => { const element = document.createElement("a"); const file = new Blob([document.getElementById('myInput').value], {type: 'text/plain'}); element.href = URL.createObjectURL(file); element.download = "myFile.txt"; document.body.appendChild(element); // Required for this to work in FireFox element.click(); } render() { return ( <div> <input id="myInput" /> <button onClick={this.downloadTxtFile}>Download txt</button> </div> ); } } ReactDOM.render(<MyApp />, document.getElementById("myApp")); <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="myApp"></div>