源码:github:
https://github.com/xiaofengz/react-blog
首页效果:
markdown:
EditorMarkdown.js (编辑器组件)
- 使用ReactMarkDown:github(http://github.com/rexxars/react-markdown)
- 可选CodeMirror 一个支持语法高亮、自动缩进、智能提示等功能的编辑器
import React, {Component} from 'react';
// import CodeMirror from 'COMPONENTS/CodeMirror';
import { Input } from 'antd';
import ReactMarkdown from 'react-markdown';
import CodeBlock from "COMPONENTS/CodeBlock"
const { TextArea } = Input;
class EditorMarkdown extends Component {
constructor (props) {
super(props)
this.state = {
value:''
}
}
componentDidMount () {
}
updateCode(e) {
this.setState({
value: e.target.value,
});
console.log(e.keyCode)
if (e.keyCode == 9) {
alert('tab!')
}
}
checkTab (e) {
if (e.keyCode == 9) {
e.preventDefault();
this.setState({
value:this.state.value + ' '
})
}
console.log('value',e.target.value)
}
render() {
return <div>
<div style={{"height":"100vh","width":"50%",float:"left"}}>
{/* <CodeMirror value={this.state.value} onChange={this.updateCode.bind(this)}/> */}
<TextArea style={{width:"100%",height:"100%",padding:"40px 40px",fontSize:"16px"}} value={this.state.value} onChange={this.updateCode.bind(this)} onKeyDown={this.checkTab.bind(this)}></TextArea>
</div>
<ReactMarkdown className="result"
source={this.state.value}
renderers={{code: CodeBlock}}
/>
</div>
}
}
export default EditorMarkdown;
- CodeBlock (使用highlight实现 代码高亮)
https://github.com/isagalaev/highlight.js
import React, {PureComponent} from 'react';
const hljs = window.hljs
class CodeBlock extends PureComponent {
constructor(props) {
super(props)
this.setRef = this.setRef.bind(this)
}
componentDidMount() {
this.highlightCode()
}
setRef(el) {
this.codeEl = el
}
componentDidUpdate() {
this.highlightCode()
}
highlightCode() {
hljs.highlightBlock(this.codeEl)
}
render() {
return (
<pre>
<code ref={this.setRef} className={this.props.language}>
{this.props.value}
</code>
</pre>
)
}
}
export default CodeBlock;