diff --git a/.gitignore b/.gitignore index 035cf012ab..6077544a4f 100644 --- a/.gitignore +++ b/.gitignore @@ -4,8 +4,7 @@ logs npm-debug.log* yarn-debug.log* yarn-error.log* -package-lock.json -yarn.lock + # Runtime data pids *.pid @@ -60,22 +59,12 @@ typings/ # next.js build output .next -next/ -# special demo file for locally reappear issue -docs/**/demo/issues.md precss.css .sass-cache/ -scripts/server-remote -__html/ -dist/ -es/ -lib/ test/coverage/ test/**/coverage/ -compiled_docs/ -demos/ platform-docs/ coverage/ docs-lang/ diff --git a/compiled_docs/affix/demo/absolute-position.en-us.md b/compiled_docs/affix/demo/absolute-position.en-us.md new file mode 100644 index 0000000000..63c9a31036 --- /dev/null +++ b/compiled_docs/affix/demo/absolute-position.en-us.md @@ -0,0 +1 @@ +{"title":"Container","meta":{"title":"Container","description":"\n
Change the default container by passing a function to container
;\nenable useAbsolute
to use absolute position
to implement affix component;
import { Affix, Button } from '@alifd/next';\n\nclass Demo extends React.Component {\n\n _containerRefHandler(ref) {\n this.container = ref;\n }\n\n render() {\n return (\n <div className=\"custom-affix-container\" ref={this._containerRefHandler.bind(this)}>\n <div className=\"affix-wrapper\">\n <Affix container={() => this.container} offsetTop={0} useAbsolute>\n <Button type=\"secondary\">Affixed Button</Button>\n </Affix>\n </div>\n </div>\n );\n }\n}\n\n\n\nReactDOM.render(<Demo />, mountNode);
.custom-affix-container {\n height: 150px;\n overflow-y: scroll;\n background: url(https://img.alicdn.com/tfs/TB1AbJXSpXXXXXJXpXXXXXXXXXX-32-32.jpg) repeat 50% 50%;\n}\n\n.custom-affix-container .affix-wrapper {\n padding-top: 100px;\n height: 500px;\n}
可以通过 container
属性设置 Affix 组件需要监听其滚动事件的元素,该属性接收一个函数作为参数,默认为 () => window
;\n设置 useAbsolute 为 true,通过 absolute 布局实现组件固定。
import { Affix, Button } from '@alifd/next';\n\nclass Demo extends React.Component {\n\n _containerRefHandler(ref) {\n this.container = ref;\n }\n\n render() {\n return (\n <div className=\"custom-affix-container\" ref={this._containerRefHandler.bind(this)}>\n <div className=\"affix-wrapper\">\n <Affix container={() => this.container} offsetTop={0} useAbsolute>\n <Button type=\"secondary\">Affixed Button</Button>\n </Affix>\n </div>\n </div>\n );\n }\n}\n\n\n\nReactDOM.render(<Demo />, mountNode);
.custom-affix-container {\n height: 150px;\n overflow-y: scroll;\n background: url(https://img.alicdn.com/tfs/TB1AbJXSpXXXXXJXpXXXXXXXXXX-32-32.jpg) repeat 50% 50%;\n}\n\n.custom-affix-container .affix-wrapper {\n padding-top: 100px;\n height: 500px;\n}
The simple usage is to wrap your components direcly with Affix component.
\n","order":"0"},"codes":{"jsx":"import { Affix, Button } from '@alifd/next';\n\nReactDOM.render(import { Affix, Button } from '@alifd/next';\n\nReactDOM.render(<div className=\"custom-affix-wrapper\">\n <Affix>\n <Button type=\"secondary\">Affixed Button</Button>\n </Affix>\n</div>, mountNode);
.custom-affix-wrapper {\n padding: 40px 0;\n}
默认情况下,Affix 的默认目标容器元素是整个 window
,并且 offsetTop = 0
,\n也就意味着当页面往下滚动时,当 Affix 元素接触到浏览器边框时,此时会将 Affix 钉住。
import { Affix, Button } from '@alifd/next';\n\nReactDOM.render(<div className=\"custom-affix-wrapper\">\n <Affix>\n <Button type=\"secondary\">Affixed Button</Button>\n </Affix>\n</div>, mountNode);
.custom-affix-wrapper {\n padding: 40px 0;\n}
Change the default container by passing a function to container
.
import { Affix, Button } from '@alifd/next';\n\nclass Demo extends React.Component {\n\n _containerRefHandler(ref) {\n this.container = ref;\n }\n\n render() {\n return (\n <div className=\"custom-affix-container\" ref={this._containerRefHandler.bind(this)}>\n <div className=\"affix-wrapper\">\n <Affix container={() => this.container} offsetTop={0}>\n <Button type=\"secondary\">Affixed Button</Button>\n </Affix>\n </div>\n </div>\n );\n }\n}\n\n\n\nReactDOM.render(<Demo />, mountNode);
.custom-affix-container {\n height: 150px;\n overflow-y: scroll;\n background: url(https://img.alicdn.com/tfs/TB1AbJXSpXXXXXJXpXXXXXXXXXX-32-32.jpg) repeat 50% 50%;\n}\n\n.custom-affix-container .affix-wrapper {\n padding-top: 50px;\n height: 500px;\n}
可以通过 container
属性设置 Affix 组件需要监听其滚动事件的元素,该属性接收一个函数作为参数,默认为 () => window
。
import { Affix, Button } from '@alifd/next';\n\nclass Demo extends React.Component {\n\n _containerRefHandler(ref) {\n this.container = ref;\n }\n\n render() {\n return (\n <div className=\"custom-affix-container\" ref={this._containerRefHandler.bind(this)}>\n <div className=\"affix-wrapper\">\n <Affix container={() => this.container} offsetTop={0}>\n <Button type=\"secondary\">Affixed Button</Button>\n </Affix>\n </div>\n </div>\n );\n }\n}\n\n\n\nReactDOM.render(<Demo />, mountNode);
.custom-affix-container {\n height: 150px;\n overflow-y: scroll;\n background: url(https://img.alicdn.com/tfs/TB1AbJXSpXXXXXJXpXXXXXXXXXX-32-32.jpg) repeat 50% 50%;\n}\n\n.custom-affix-container .affix-wrapper {\n padding-top: 50px;\n height: 500px;\n}
Setting the offset by offsetTop
or offsetBottom
.
import { Affix, Button } from '@alifd/next';\n\nReactDOM.render(<div className=\"custom-affix-wrapper\">\n <Affix offsetBottom={0}>\n <Button type=\"secondary\">Affixed Button</Button>\n </Affix>\n</div>, mountNode);
.custom-affix-wrapper {\n padding: 40px 0;\n}
可以通过 offsetTop
或 offsetBottom
自定义偏移量。
import { Affix, Button } from '@alifd/next';\n\nReactDOM.render(<div className=\"custom-affix-wrapper\">\n <Affix offsetBottom={0}>\n <Button type=\"secondary\">Affixed Button</Button>\n </Affix>\n</div>, mountNode);
.custom-affix-wrapper {\n padding: 40px 0;\n}
Listening the affix state by onAffix
.
import { Affix, Button } from '@alifd/next';\n\nclass Demo extends React.Component {\n\n constructor(props) {\n super(props);\n this.state = {\n affixed: false\n };\n }\n\n onAffix = (affixed) => {\n this.setState({\n affixed\n });\n }\n\n render() {\n const state = this.state;\n\n return (<div className=\"affix-demo-wrapper\">\n <Affix onAffix={this.onAffix}>\n <Button type=\"secondary\">{state.affixed ? 'Affixed Button' : 'Unaffixed Button'}</Button>\n </Affix>\n </div>);\n }\n}\n\n\nReactDOM.render(<Demo />, mountNode);
.affix-demo-wrapper {\n padding: 40px 0;\n}
可以通过传入 onAffix
的事件回调函数来监听元素是否发生了固钉状态。该函数会在状态变化时返回固钉状态。
import { Affix, Button } from '@alifd/next';\n\nclass Demo extends React.Component {\n\n constructor(props) {\n super(props);\n this.state = {\n affixed: false\n };\n }\n\n onAffix = (affixed) => {\n this.setState({\n affixed\n });\n }\n\n render() {\n const state = this.state;\n\n return (<div className=\"affix-demo-wrapper\">\n <Affix onAffix={this.onAffix}>\n <Button type=\"secondary\">{state.affixed ? 'Affixed Button' : 'Unaffixed Button'}</Button>\n </Affix>\n </div>);\n }\n}\n\n\nReactDOM.render(<Demo />, mountNode);
.affix-demo-wrapper {\n padding: 40px 0;\n}
The Affix component allows an element to become affixed (locked) to an area on the page. This is offten used with navigation menus or social icon buttons, to make them "stick" at specific area while scrolling up and down the page.
\nParam | \nDescription | \nType | \nDefault Value | \n
---|---|---|---|
container | \nThe container for listening scroll events signature: Function() => ReactElement return: {ReactElement} the instance of container | \nFunction | \n() => window | \n
offsetTop | \nOffset from top when event triggers | \nNumber | \n- | \n
offsetBottom | \nOffset from bottom when event triggers | \nNumber | \n- | \n
onAffix | \nCallback when affix event triggers signature: Function(isAffixed: Boolean) => void parameters: if element is affixed: {Boolean} null | \nFunction | \nfunc.noop | \n
useAbsolute | \nEnable absolute position | \nBoolean | \n- | \n
当用户需要将某个组件固定在页面的某个位置时,可以使用 Affix 组件进行固定。
\n参数 | \n说明 | \n类型 | \n默认值 | \n
---|---|---|---|
container | \n设置 Affix 需要监听滚动事件的容器元素 签名: Function() => ReactElement 返回值: {ReactElement} 目标容器元素的实例 | \nFunction | \n() => window | \n
offsetTop | \n距离窗口顶部达到指定偏移量后触发 | \nNumber | \n- | \n
offsetBottom | \n距离窗口底部达到制定偏移量后触发 | \nNumber | \n- | \n
onAffix | \n当元素的样式发生固钉样式变化时触发的回调函数 签名: Function(affixed: Boolean) => void 参数: affixed: {Boolean} 元素是否被固钉 | \nFunction | \nfunc.noop | \n
useAbsolute | \n是否启用绝对布局实现 affix | \nBoolean | \n- | \n
Demo the enter and leave animation of a child element.
\n","order":"0"},"codes":{"jsx":"import { Animate } from '@alifd/next';\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n this.state = { visible: true };\n this.handleToggle = this.handleToggle.bind(this);\n }\n\n handleToggle() {\n this.setState({\n visible: !this.state.visible\n });\n }\n\n render() {\n return (\nimport { Animate } from '@alifd/next';\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n this.state = { visible: true };\n this.handleToggle = this.handleToggle.bind(this);\n }\n\n handleToggle() {\n this.setState({\n visible: !this.state.visible\n });\n }\n\n render() {\n return (\n <div>\n <button onClick={this.handleToggle}>Toggle visible</button>\n <Animate animation={{\n enter: 'my-zoom-in',\n leave: 'my-zoom-out'\n }}>\n {this.state.visible ?\n <div className=\"basic-demo\">Next Animate</div> :\n null}\n </Animate>\n </div>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
.basic-demo {\n font-size: 96px;\n text-align: center;\n}\n\n.my-zoom-in {\n opacity: 0;\n}\n\n.my-zoom-in-active {\n animation: my-zoom-in 500ms linear;\n}\n\n.my-zoom-out {\n opacity: 1;\n}\n\n.my-zoom-out-active {\n animation: my-zoom-out 500ms linear;\n}\n\n@keyframes my-zoom-in {\n from {\n opacity: 0;\n transform: scale3d(.3, .3, .3);\n }\n\n 50% {\n opacity: 1;\n }\n\n to {\n opacity: 1;\n }\n}\n\n@keyframes my-zoom-out {\n from {\n opacity: 1;\n }\n\n 50% {\n opacity: 0;\n transform: scale3d(.3, .3, .3);\n }\n\n to {\n opacity: 0;\n }\n}
展示单个子元素的进场离场动画。
\n","order":"0"},"codes":{"jsx":"import { Animate } from '@alifd/next';\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n this.state = { visible: true };\n this.handleToggle = this.handleToggle.bind(this);\n }\n\n handleToggle() {\n this.setState({\n visible: !this.state.visible\n });\n }\n\n render() {\n return (\nimport { Animate } from '@alifd/next';\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n this.state = { visible: true };\n this.handleToggle = this.handleToggle.bind(this);\n }\n\n handleToggle() {\n this.setState({\n visible: !this.state.visible\n });\n }\n\n render() {\n return (\n <div>\n <button onClick={this.handleToggle}>Toggle visible</button>\n <Animate animation={{\n enter: 'my-zoom-in',\n leave: 'my-zoom-out'\n }}>\n {this.state.visible ?\n <div className=\"basic-demo\">Next Animate</div> :\n null}\n </Animate>\n </div>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
.basic-demo {\n font-size: 96px;\n text-align: center;\n}\n\n.my-zoom-in {\n opacity: 0;\n}\n\n.my-zoom-in-active {\n animation: my-zoom-in 500ms linear;\n}\n\n.my-zoom-out {\n opacity: 1;\n}\n\n.my-zoom-out-active {\n animation: my-zoom-out 500ms linear;\n}\n\n@keyframes my-zoom-in {\n from {\n opacity: 0;\n transform: scale3d(.3, .3, .3);\n }\n\n 50% {\n opacity: 1;\n }\n\n to {\n opacity: 1;\n }\n}\n\n@keyframes my-zoom-out {\n from {\n opacity: 1;\n }\n\n 50% {\n opacity: 0;\n transform: scale3d(.3, .3, .3);\n }\n\n to {\n opacity: 0;\n }\n}
Demo the expand and collapse animation of a child element.
\n","order":"2"},"codes":{"jsx":"import { Animate } from '@alifd/next';\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n this.state = { expand: true };\n ['beforeEnter', 'onEnter', 'afterEnter', 'beforeLeave', 'onLeave', 'afterLeave', 'handleToggle'].forEach(method => {\n this[method] = this[method].bind(this);\n });\n }\n\n handleToggle() {\n this.setState({\n expand: !this.state.expand\n });\n }\n\n beforeEnter(node) {\n this.height = node.offsetHeight;\n node.style.height = '0px';\n }\n\n onEnter(node) {\n node.style.height = `${this.height}px`;\n }\n\n afterEnter(node) {\n this.height = null;\n node.style.height = null;\n }\n\n beforeLeave(node) {\n node.style.height = `${this.height}px`;\n }\n\n onLeave(node) {\n node.style.height = '0px';\n }\n\n afterLeave(node) {\n node.style.height = null;\n }\n\n render() {\n return (\nimport { Animate } from '@alifd/next';\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n this.state = { expand: true };\n ['beforeEnter', 'onEnter', 'afterEnter', 'beforeLeave', 'onLeave', 'afterLeave', 'handleToggle'].forEach(method => {\n this[method] = this[method].bind(this);\n });\n }\n\n handleToggle() {\n this.setState({\n expand: !this.state.expand\n });\n }\n\n beforeEnter(node) {\n this.height = node.offsetHeight;\n node.style.height = '0px';\n }\n\n onEnter(node) {\n node.style.height = `${this.height}px`;\n }\n\n afterEnter(node) {\n this.height = null;\n node.style.height = null;\n }\n\n beforeLeave(node) {\n node.style.height = `${this.height}px`;\n }\n\n onLeave(node) {\n node.style.height = '0px';\n }\n\n afterLeave(node) {\n node.style.height = null;\n }\n\n render() {\n return (\n <div>\n <button onClick={this.handleToggle}>Toggle expand</button>\n <Animate animation=\"expand\"\n beforeEnter={this.beforeEnter}\n onEnter={this.onEnter}\n afterEnter={this.afterEnter}\n beforeLeave={this.beforeLeave}\n onLeave={this.onLeave}\n afterLeave={this.afterLeave}>\n {this.state.expand ?\n <div className=\"notice\"></div> :\n null}\n </Animate>\n </div>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
.expand-enter {\n overflow: hidden;\n}\n\n.expand-enter-active {\n transition: height 0.3s ease-out;\n}\n\n.expand-leave {\n overflow: hidden;\n}\n\n.expand-leave-active {\n transition: height 0.3s ease-out;\n}\n\n.notice {\n width: 200px;\n height: 100px;\n margin-top: 20px;\n border: 1px solid #ccc;\n}
展示单个子元素的展开收起动画。
\n","order":"2"},"codes":{"jsx":"import { Animate } from '@alifd/next';\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n this.state = { expand: true };\n ['beforeEnter', 'onEnter', 'afterEnter', 'beforeLeave', 'onLeave', 'afterLeave', 'handleToggle'].forEach(method => {\n this[method] = this[method].bind(this);\n });\n }\n\n handleToggle() {\n this.setState({\n expand: !this.state.expand\n });\n }\n\n beforeEnter(node) {\n this.height = node.offsetHeight;\n node.style.height = '0px';\n }\n\n onEnter(node) {\n node.style.height = `${this.height}px`;\n }\n\n afterEnter(node) {\n this.height = null;\n node.style.height = null;\n }\n\n beforeLeave(node) {\n node.style.height = `${this.height}px`;\n }\n\n onLeave(node) {\n node.style.height = '0px';\n }\n\n afterLeave(node) {\n node.style.height = null;\n }\n\n render() {\n return (\nimport { Animate } from '@alifd/next';\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n this.state = { expand: true };\n ['beforeEnter', 'onEnter', 'afterEnter', 'beforeLeave', 'onLeave', 'afterLeave', 'handleToggle'].forEach(method => {\n this[method] = this[method].bind(this);\n });\n }\n\n handleToggle() {\n this.setState({\n expand: !this.state.expand\n });\n }\n\n beforeEnter(node) {\n this.height = node.offsetHeight;\n node.style.height = '0px';\n }\n\n onEnter(node) {\n node.style.height = `${this.height}px`;\n }\n\n afterEnter(node) {\n this.height = null;\n node.style.height = null;\n }\n\n beforeLeave(node) {\n node.style.height = `${this.height}px`;\n }\n\n onLeave(node) {\n node.style.height = '0px';\n }\n\n afterLeave(node) {\n node.style.height = null;\n }\n\n render() {\n return (\n <div>\n <button onClick={this.handleToggle}>Toggle expand</button>\n <Animate animation=\"expand\"\n beforeEnter={this.beforeEnter}\n onEnter={this.onEnter}\n afterEnter={this.afterEnter}\n beforeLeave={this.beforeLeave}\n onLeave={this.onLeave}\n afterLeave={this.afterLeave}>\n {this.state.expand ?\n <div className=\"notice\"></div> :\n null}\n </Animate>\n </div>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
.expand-enter {\n overflow: hidden;\n}\n\n.expand-enter-active {\n transition: height 0.3s ease-out;\n}\n\n.expand-leave {\n overflow: hidden;\n}\n\n.expand-leave-active {\n transition: height 0.3s ease-out;\n}\n\n.notice {\n width: 200px;\n height: 100px;\n margin-top: 20px;\n border: 1px solid #ccc;\n}
Demo the enter and leave animation of multiple child elements.
\n","order":"1"},"codes":{"jsx":"import { Animate } from '@alifd/next';\n\nclass TodoList extends React.Component {\n constructor(props) {\n super(props);\n this.state = { items: ['hello', 'world', 'click', 'me'] };\n }\n\n handleAdd() {\n this.setState({\n items: [\n ...this.state.items,\n // eslint-disable-next-line\n prompt('Enter some text')\n ]\n });\n }\n\n handleRemove(i) {\n const newItems = this.state.items.slice();\n newItems.splice(i, 1);\n this.setState({ items: newItems });\n }\n\n render() {\n return (\nimport { Animate } from '@alifd/next';\n\nclass TodoList extends React.Component {\n constructor(props) {\n super(props);\n this.state = { items: ['hello', 'world', 'click', 'me'] };\n }\n\n handleAdd() {\n this.setState({\n items: [\n ...this.state.items,\n // eslint-disable-next-line\n prompt('Enter some text')\n ]\n });\n }\n\n handleRemove(i) {\n const newItems = this.state.items.slice();\n newItems.splice(i, 1);\n this.setState({ items: newItems });\n }\n\n render() {\n return (\n <div className=\"totolist-container\">\n <Animate animationAppear animation=\"fade\" className=\"todo-list\" singleMode={false}\n beforeAppear={() => console.log('before appear')}\n onAppear={() => console.log('appear')}\n afterAppear={() => console.log('after appear')}\n beforeEnter={() => console.log('before enter')}\n onEnter={() => console.log('enter')}\n afterEnter={() => console.log('after enter')}\n beforeLeave={() => console.log('before leave')}\n onLeave={() => console.log('leave')}\n afterLeave={() => console.log('after leave')}>\n {this.state.items.map((item, i) => (\n <div key={item}>\n {item}\n <button onClick={() => this.handleRemove(i)}>\n ×\n </button>\n </div>\n ))}\n </Animate>\n <button onClick={() => this.handleAdd()}>Add Item</button>\n </div>\n );\n }\n}\n\nReactDOM.render(<TodoList />, mountNode);
.fade-appear {\n opacity: 0.01;\n}\n\n.fade-appear.fade-appear-active {\n opacity: 1;\n transition: opacity 1000ms ease-in;\n}\n\n.fade-enter {\n opacity: 0.01;\n}\n\n.fade-enter.fade-enter-active {\n opacity: 1;\n transition: opacity 1000ms ease-in;\n}\n\n.fade-leave {\n opacity: 1;\n}\n\n.fade-leave.fade-leave-active {\n opacity: 0.01;\n transition: opacity 800ms ease-in;\n}\n\n.totolist-container {\n padding: 20px;\n border: 1px solid #ccc;\n width: 200px;\n border-radius: 4px;\n}\n\n.todo-list > * {\n margin: 5px 0;\n padding: 5px 0;\n border-bottom: 1px solid #ccc;\n}\n\n.totolist-container > button {\n margin-top: 20px;\n}
展示多个子元素的进场离场动画。
\n","order":"1"},"codes":{"jsx":"import { Animate } from '@alifd/next';\n\nclass TodoList extends React.Component {\n constructor(props) {\n super(props);\n this.state = { items: ['hello', 'world', 'click', 'me'] };\n }\n\n handleAdd() {\n this.setState({\n items: [\n ...this.state.items,\n // eslint-disable-next-line\n prompt('Enter some text')\n ]\n });\n }\n\n handleRemove(i) {\n const newItems = this.state.items.slice();\n newItems.splice(i, 1);\n this.setState({ items: newItems });\n }\n\n render() {\n return (\nimport { Animate } from '@alifd/next';\n\nclass TodoList extends React.Component {\n constructor(props) {\n super(props);\n this.state = { items: ['hello', 'world', 'click', 'me'] };\n }\n\n handleAdd() {\n this.setState({\n items: [\n ...this.state.items,\n // eslint-disable-next-line\n prompt('Enter some text')\n ]\n });\n }\n\n handleRemove(i) {\n const newItems = this.state.items.slice();\n newItems.splice(i, 1);\n this.setState({ items: newItems });\n }\n\n render() {\n return (\n <div className=\"totolist-container\">\n <Animate animationAppear animation=\"fade\" className=\"todo-list\" singleMode={false}\n beforeAppear={() => console.log('before appear')}\n onAppear={() => console.log('appear')}\n afterAppear={() => console.log('after appear')}\n beforeEnter={() => console.log('before enter')}\n onEnter={() => console.log('enter')}\n afterEnter={() => console.log('after enter')}\n beforeLeave={() => console.log('before leave')}\n onLeave={() => console.log('leave')}\n afterLeave={() => console.log('after leave')}>\n {this.state.items.map((item, i) => (\n <div key={item}>\n {item}\n <button onClick={() => this.handleRemove(i)}>\n ×\n </button>\n </div>\n ))}\n </Animate>\n <button onClick={() => this.handleAdd()}>Add Item</button>\n </div>\n );\n }\n}\n\nReactDOM.render(<TodoList />, mountNode);
.fade-appear {\n opacity: 0.01;\n}\n\n.fade-appear.fade-appear-active {\n opacity: 1;\n transition: opacity 1000ms ease-in;\n}\n\n.fade-enter {\n opacity: 0.01;\n}\n\n.fade-enter.fade-enter-active {\n opacity: 1;\n transition: opacity 1000ms ease-in;\n}\n\n.fade-leave {\n opacity: 1;\n}\n\n.fade-leave.fade-leave-active {\n opacity: 0.01;\n transition: opacity 800ms ease-in;\n}\n\n.totolist-container {\n padding: 20px;\n border: 1px solid #ccc;\n width: 200px;\n border-radius: 4px;\n}\n\n.todo-list > * {\n margin: 5px 0;\n padding: 5px 0;\n border-bottom: 1px solid #ccc;\n}\n\n.totolist-container > button {\n margin-top: 20px;\n}
Need to customize animation.
\nParam | \nDescripiton | \nType | \nDefault Value | \n
---|---|---|---|
animation | \nanimation class names | \nString/Object | \n- | \n
animationAppear | \nwhether the child elements performs animation when it is first mounted | \nBoolean | \ntrue | \n
component | \ncomponent wrapped child element | \nany | \n'div' | \n
singleMode | \nwhether there is only a single child element, if there is more than one child element, set it to false | \nBoolean | \ntrue | \n
children | \nchild elements | \nReactElement/Array<ReactElement> | \n- | \n
beforeAppear | \ntriggered before performing the first mount animation signatures: Function() => void | \nFunction | \n() => {} | \n
onAppear | \ntriggered after adding the xxx-appear-active class name signatures: Function(node: HTMLElement) => void params: node: {HTMLElement} \banimated dom element | \nFunction | \n() => {} | \n
afterAppear | \ntriggered after performing the first mount animation signatures: Function(node: HTMLElement) => void params: node: {HTMLElement} \banimated dom element | \nFunction | \n() => {} | \n
beforeEnter | \ntriggered before performing the enter animation signatures: Function(node: HTMLElement) => void params: node: {HTMLElement} \banimated dom element | \nFunction | \n() => {} | \n
onEnter | \ntriggered after adding the xxx-enter-active class name signatures: Function(node: HTMLElement) => void params: node: {HTMLElement} \banimated dom element | \nFunction | \n() => {} | \n
afterEnter | \ntriggered after performing the enter animation signatures: Function(node: HTMLElement) => void params: node: {HTMLElement} \banimated dom element | \nFunction | \n() => {} | \n
beforeLeave | \ntriggered before performing the leave animation signatures: Function(node: HTMLElement) => void params: node: {HTMLElement} \banimated dom element | \nFunction | \n() => {} | \n
onLeave | \ntriggered after adding the xxx-leave-active class name signatures: Function(node: HTMLElement) => void params: node: {HTMLElement} \banimated dom element | \nFunction | \n() => {} | \n
afterLeave | \ntriggered after performing the leave animation signatures: Function(node: HTMLElement) => void params: node: {HTMLElement} \banimated dom element | \nFunction | \n() => {} | \n
In | \nOut | \n
---|---|
fadeIn | \nfadeOut | \n
fadeInDown | \nfadeOutDown | \n
fadeInLeft | \nfadeOutLeft | \n
fadeInRight | \nfadeOutRight | \n
fadeInUp | \nfadeOutUp | \n
zoomIn | \nzoomOut | \n
expandInDown | \nexpandOutUp | \n
expandInUp | \nexpandOutDown | \n
pulse | \n
需要自定义动效
\n参数 | \n说明 | \n类型 | \n默认值 | \n
---|---|---|---|
animation | \n动画 className | \nString/Object | \n- | \n
animationAppear | \n子元素第一次挂载时是否执行动画 | \nBoolean | \ntrue | \n
component | \n包裹子元素的标签 | \nany | \n'div' | \n
singleMode | \n是否只有单个子元素,如果有多个子元素,请设置为 false | \nBoolean | \ntrue | \n
children | \n子元素 | \nReactElement/Array<ReactElement> | \n- | \n
beforeAppear | \n执行第一次挂载动画前触发的回调函数 签名: Function(node: HTMLElement) => void 参数: node: {HTMLElement} \b执行动画的 dom 元素 | \nFunction | \n() => {} | \n
onAppear | \n执行第一次挂载动画,添加 xxx-appear-active 类名后触发的回调函数 签名: Function(node: HTMLElement) => void 参数: node: {HTMLElement} \b执行动画的 dom 元素 | \nFunction | \n() => {} | \n
afterAppear | \n执行完第一次挂载动画后触发的函数 签名: Function(node: HTMLElement) => void 参数: node: {HTMLElement} \b执行动画的 dom 元素 | \nFunction | \n() => {} | \n
beforeEnter | \n执行进场动画前触发的回调函数 签名: Function(node: HTMLElement) => void 参数: node: {HTMLElement} \b执行动画的 dom 元素 | \nFunction | \n() => {} | \n
onEnter | \n执行进场动画,添加 xxx-enter-active 类名后触发的回调函数 签名: Function(node: HTMLElement) => void 参数: node: {HTMLElement} \b执行动画的 dom 元素 | \nFunction | \n() => {} | \n
afterEnter | \n执行完进场动画后触发的回调函数 签名: Function(node: HTMLElement) => void 参数: node: {HTMLElement} \b执行动画的 dom 元素 | \nFunction | \n() => {} | \n
beforeLeave | \n执行离场动画前触发的回调函数 签名: Function(node: HTMLElement) => void 参数: node: {HTMLElement} \b执行动画的 dom 元素 | \nFunction | \n() => {} | \n
onLeave | \n执行离场动画,添加 xxx-leave-active 类名后触发的回调函数 签名: Function(node: HTMLElement) => void 参数: node: {HTMLElement} \b执行动画的 dom 元素 | \nFunction | \n() => {} | \n
afterLeave | \n执行完离场动画后触发的回调函数 签名: Function(node: HTMLElement) => void 参数: node: {HTMLElement} \b执行动画的 dom 元素 | \nFunction | \n() => {} | \n
In | \nOut | \n
---|---|
fadeIn | \nfadeOut | \n
fadeInDown | \nfadeOutDown | \n
fadeInLeft | \nfadeOutLeft | \n
fadeInRight | \nfadeOutRight | \n
fadeInUp | \nfadeOutUp | \n
slideInDown | \nslideOutUp | \n
slideInLeft | \nslideOutLeft | \n
slideInRight | \nslideOutRight | \n
slideInUp | \nslideOutDown | \n
zoomIn | \nzoomOut | \n
expandInDown | \nexpandOutUp | \n
expandInUp | \nexpandOutDown | \n
pulse | \n
Simple usage of badge component.
\n","order":"0"},"codes":{"jsx":"import { Badge } from '@alifd/next';\n\nReactDOM.render(\nimport { Badge } from '@alifd/next';\n\nReactDOM.render(\n <div>\n <Badge count={5}>\n <a href=\"#\" className=\"basic-example\"></a>\n </Badge>\n\n <Badge count={5}>\n <a href=\"#\" className=\"basic-example\"><span className=\"next-sr-only\">unread messages</span></a>\n </Badge>\n </div>\n , mountNode);
.basic-example {\n display: inline-block;\n width: 42px;\n height: 42px;\n border-radius: 8px;\n background: #eee;\n}\n\n.next-badge {\n margin-right: 16px;\n}
简单的徽章展示。
\n","order":"0"},"codes":{"jsx":"import { Badge } from '@alifd/next';\n\nReactDOM.render(\nimport { Badge } from '@alifd/next';\n\nReactDOM.render(\n <div>\n <Badge count={5}>\n <a href=\"#\" className=\"basic-example\"></a>\n </Badge>\n\n <Badge count={5}>\n <a href=\"#\" className=\"basic-example\"><span className=\"next-sr-only\">unread messages</span></a>\n </Badge>\n </div>\n , mountNode);
.basic-example {\n display: inline-block;\n width: 42px;\n height: 42px;\n border-radius: 8px;\n background: #eee;\n}\n\n.next-badge {\n margin-right: 16px;\n}
Display the effect of dynamic changes.
\n","order":"3"},"codes":{"jsx":"import { Badge, Button, Icon } from '@alifd/next';\n\n\n\nconst ButtonGroup = Button.Group;\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n count: 5,\n show: true\n };\n\n this.increase = this.increase.bind(this);\n this.decrease = this.decrease.bind(this);\n this.onClick = this.onClick.bind(this);\n }\n\n increase() {\n const count = this.state.count + 1;\n this.setState({ count });\n }\n\n decrease() {\n let count = this.state.count - 1;\n if (count < 0) {\n count = 0;\n }\n this.setState({ count });\n }\n\n onClick() {\n this.setState({\n show: !this.state.show\n });\n }\n\n render() {\n return (\nimport { Badge, Button, Icon } from '@alifd/next';\n\n\n\nconst ButtonGroup = Button.Group;\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n count: 5,\n show: true\n };\n\n this.increase = this.increase.bind(this);\n this.decrease = this.decrease.bind(this);\n this.onClick = this.onClick.bind(this);\n }\n\n increase() {\n const count = this.state.count + 1;\n this.setState({ count });\n }\n\n decrease() {\n let count = this.state.count - 1;\n if (count < 0) {\n count = 0;\n }\n this.setState({ count });\n }\n\n onClick() {\n this.setState({\n show: !this.state.show\n });\n }\n\n render() {\n return (\n <div>\n <div className=\"change-count\">\n <Badge count={this.state.count}>\n <a href=\"#\" className=\"head-example\"><span className=\"next-sr-only\">unread messages</span></a>\n </Badge>\n <Badge count={this.state.count} showZero>\n <a href=\"#\" className=\"head-example\"><span className=\"next-sr-only\">unread messages</span></a>\n </Badge>\n <ButtonGroup>\n <Button aria-label=\"add\" onClick={this.increase}>\n <Icon type=\"add\"/>\n </Button>\n <Button aria-label=\"minus\" onClick={this.decrease}>\n <Icon type=\"minus\"/>\n </Button>\n </ButtonGroup>\n </div>\n <div>\n <Badge dot={this.state.show}>\n <a href=\"#\" className=\"head-example\"></a>\n </Badge>\n <Button onClick={this.onClick}>\n Toggle Display\n </Button>\n </div>\n </div>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
.next-badge {\n margin-right: 16px;\n}\n.change-count {\n margin-bottom: 16px;\n}\n.head-example {\n display: inline-block;\n width: 42px;\n height: 42px;\n border-radius: 8px;\n background: #eee;\n}
展示动态变化的效果。
\n","order":"3"},"codes":{"jsx":"import { Badge, Button, Icon } from '@alifd/next';\n\n\n\nconst ButtonGroup = Button.Group;\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n count: 5,\n show: true\n };\n\n this.increase = this.increase.bind(this);\n this.decrease = this.decrease.bind(this);\n this.onClick = this.onClick.bind(this);\n }\n\n increase() {\n const count = this.state.count + 1;\n this.setState({ count });\n }\n\n decrease() {\n let count = this.state.count - 1;\n if (count < 0) {\n count = 0;\n }\n this.setState({ count });\n }\n\n onClick() {\n this.setState({\n show: !this.state.show\n });\n }\n\n render() {\n return (\nimport { Badge, Button, Icon } from '@alifd/next';\n\n\n\nconst ButtonGroup = Button.Group;\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n count: 5,\n show: true\n };\n\n this.increase = this.increase.bind(this);\n this.decrease = this.decrease.bind(this);\n this.onClick = this.onClick.bind(this);\n }\n\n increase() {\n const count = this.state.count + 1;\n this.setState({ count });\n }\n\n decrease() {\n let count = this.state.count - 1;\n if (count < 0) {\n count = 0;\n }\n this.setState({ count });\n }\n\n onClick() {\n this.setState({\n show: !this.state.show\n });\n }\n\n render() {\n return (\n <div>\n <div className=\"change-count\">\n <Badge count={this.state.count}>\n <a href=\"#\" className=\"head-example\"><span className=\"next-sr-only\">unread messages</span></a>\n </Badge>\n <Badge count={this.state.count} showZero>\n <a href=\"#\" className=\"head-example\"><span className=\"next-sr-only\">unread messages</span></a>\n </Badge>\n <ButtonGroup>\n <Button aria-label=\"add\" onClick={this.increase}>\n <Icon type=\"add\"/>\n </Button>\n <Button aria-label=\"minus\" onClick={this.decrease}>\n <Icon type=\"minus\"/>\n </Button>\n </ButtonGroup>\n </div>\n <div>\n <Badge dot={this.state.show}>\n <a href=\"#\" className=\"head-example\"></a>\n </Badge>\n <Button onClick={this.onClick}>\n Toggle Display\n </Button>\n </div>\n </div>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
.next-badge {\n margin-right: 16px;\n}\n.change-count {\n margin-bottom: 16px;\n}\n.head-example {\n display: inline-block;\n width: 42px;\n height: 42px;\n border-radius: 8px;\n background: #eee;\n}
You can set value of atrribute content
to customize content of badge, customize content depend on what you code, and exclude any style.
import { Badge, Icon } from '@alifd/next';\n\nReactDOM.render(\n <div>\n <Badge content=\"hot\" style={{backgroundColor: '#FC0E3D', color: '#FFFFFF'}}>\n <a href=\"#\" className=\"head-example\"></a>\n </Badge>\n <Badge content={<Icon type=\"error\" />} style={{backgroundColor: 'transparent', color: 'red', padding: 0}}>\n <a href=\"#\" className=\"head-example\"></a>\n </Badge>\n </div>, mountNode);
.next-badge {\n margin-right: 24px;\n}\n.head-example {\n display: inline-block;\n width: 42px;\n height: 42px;\n border-radius: 8px;\n background-color: #eee;\n}
通过 content
属性可以自定义徽标的内容,自定义内容不包含任何色彩样式,完全由使用者自己定义。
import { Badge, Icon } from '@alifd/next';\n\nReactDOM.render(\n <div>\n <Badge content=\"hot\" style={{backgroundColor: '#FC0E3D', color: '#FFFFFF'}}>\n <a href=\"#\" className=\"head-example\"></a>\n </Badge>\n <Badge content={<Icon type=\"error\" />} style={{backgroundColor: 'transparent', color: 'red', padding: 0}}>\n <a href=\"#\" className=\"head-example\"></a>\n </Badge>\n </div>, mountNode);
.next-badge {\n margin-right: 24px;\n}\n.head-example {\n display: inline-block;\n width: 42px;\n height: 42px;\n border-radius: 8px;\n background-color: #eee;\n}
Just a red dot, not a number.
\n","order":"2"},"codes":{"jsx":"import { Badge, Icon } from '@alifd/next';\n\nReactDOM.render(\nimport { Badge, Icon } from '@alifd/next';\n\nReactDOM.render(\n <div>\n <Badge dot>\n <Icon type=\"email\" />\n </Badge>\n <Badge dot>\n <a href=\"#\">A Link</a>\n </Badge>\n </div>, mountNode);
.next-badge {\n margin-right: 16px;\n}
没有具体的数字。
\n","order":"2"},"codes":{"jsx":"import { Badge, Icon } from '@alifd/next';\n\nReactDOM.render(\nimport { Badge, Icon } from '@alifd/next';\n\nReactDOM.render(\n <div>\n <Badge dot>\n <Icon type=\"email\" />\n </Badge>\n <Badge dot>\n <a href=\"#\">A Link</a>\n </Badge>\n </div>, mountNode);
.next-badge {\n margin-right: 16px;\n}
Alone usage mean that badge component wrap nothing, and you can custom style of badge component.
\n","order":"5"},"codes":{"jsx":"import { Badge } from '@alifd/next';\n\nReactDOM.render(\nimport { Badge } from '@alifd/next';\n\nReactDOM.render(\n <div>\n <Badge count={25} />\n <Badge count={4} style={{backgroundColor: '#fff', color: '#999', border: '1px solid #d9d9d9'}} />\n <Badge count={109} style={{backgroundColor: '#87d068'}} />\n <Badge dot />\n <Badge content=\"hot\" style={{backgroundColor: '#FC0E3D', color: '#FFFFFF'}} />\n </div>, mountNode);
.next-badge {\n margin-right: 16px;\n}
不包裹任何元素即独立使用,可自定样式展示。
\n","order":"5"},"codes":{"jsx":"import { Badge } from '@alifd/next';\n\nReactDOM.render(\nimport { Badge } from '@alifd/next';\n\nReactDOM.render(\n <div>\n <Badge count={25} />\n <Badge count={4} style={{backgroundColor: '#fff', color: '#999', border: '1px solid #d9d9d9'}} />\n <Badge count={109} style={{backgroundColor: '#87d068'}} />\n <Badge dot />\n <Badge content=\"hot\" style={{backgroundColor: '#FC0E3D', color: '#FFFFFF'}} />\n </div>, mountNode);
.next-badge {\n margin-right: 16px;\n}
Display \\${overflowCount}+
when count is greater than overflowCount, default value of overflow is 99
.
import { Badge } from '@alifd/next';\n\nReactDOM.render(\n <div>\n <Badge count={100}>\n <a href=\"#\" className=\"head-example\"></a>\n </Badge>\n <Badge count={200} overflowCount={199}>\n <a href=\"#\" className=\"head-example\"></a>\n </Badge>\n </div>, mountNode);
.next-badge {\n margin-right: 16px;\n}\n.head-example {\n display: inline-block;\n width: 42px;\n height: 42px;\n border-radius: 8px;\n background: #eee;\n}
超过overflow的数值,会显示\\${overflow}+
,overflow默认值为99
。
import { Badge } from '@alifd/next';\n\nReactDOM.render(\n <div>\n <Badge count={100}>\n <a href=\"#\" className=\"head-example\"></a>\n </Badge>\n <Badge count={200} overflowCount={199}>\n <a href=\"#\" className=\"head-example\"></a>\n </Badge>\n </div>, mountNode);
.next-badge {\n margin-right: 16px;\n}\n.head-example {\n display: inline-block;\n width: 42px;\n height: 42px;\n border-radius: 8px;\n background: #eee;\n}
When we receive a new message, or our app/plugin/module should be update or upgrade.
\nYou can add class as below, so that messages will not appear on pages, but can be read by screen reader.\n<span className="next-sr-only">unread messages</span>
Param | \nDescripiton | \nType | \nDefault Value | \n
---|---|---|---|
children | \ncontent of Badge based on | \nReactNode | \n- | \n
count | \nnumber to display, display ${overflowCount}+ when count is greater than overflowCount, display none when count equal to 0 | \nNumber/String | \n0 | \n
showZero | \nwhether to show count when count is 0 | \nBoolean | \nfalse | \n
content | \ncustomized node content | \nReactNode | \n- | \n
overflowCount | \nmax number to display | \nNumber/String | \n99 | \n
dot | \ndisplay a red dot, not a number | \nBoolean | \nfalse | \n
在有新消息、讯息时,或者是app/插件/功能模块可以更新、升级时使用这个组件。
\n可通过添加如下class,使内容仅能被读屏软件读取,但不会展示到页面上\n<span className="next-sr-only">unread messages</span>
参数 | \n说明 | \n类型 | \n默认值 | \n
---|---|---|---|
children | \n徽章依托的内容 | \nReactNode | \n- | \n
count | \n展示的数字,大于 overflowCount 时显示为 ${overflowCount}+,为 0 时默认隐藏 | \nNumber/String | \n0 | \n
showZero | \n当count为0时,是否显示count | \nBoolean | \nfalse | \n
content | \n自定义节点内容 | \nReactNode | \n- | \n
overflowCount | \n展示的封顶的数字 | \nNumber/String | \n99 | \n
dot | \n不展示数字,只展示一个小红点 | \nBoolean | \nfalse | \n
id of popup. only when you set value, balloon will support accessibility.
\n","order":"8"},"codes":{"jsx":"\nimport { Button, Balloon, Input } from '@alifd/next';\nimport moment from 'moment';\n\nconst { Tooltip } = Balloon;\nconst innerButton = ;\nconst triggerTooltip = ;\n\nconst App = () => (\nThis is content for tooltip.
\nThis is content for tooltip.
\n\nimport { Button, Balloon, Input } from '@alifd/next';\nimport moment from 'moment';\n\nconst { Tooltip } = Balloon;\nconst innerButton = <Button className=\"btrigger\">Fill in form</Button>;\nconst triggerTooltip = <Button style={{margin: '5px'}}>show tooltip</Button>;\n\nconst App = () => (\n <div className=\"container nested\">\n <Balloon id=\"inner-a11y-balloon-1\" autoFocus trigger={<Button type=\"primary\">Fill in sub-form</Button>} popupContainer={(trigger) => trigger.parentNode} triggerType=\"click\">\n please input your age:\n <Input placeholder=\"Age\" size=\"small\" label=\"Age :\" id=\"balloon-input-1\" /><br /><br />\n </Balloon>\n\n \n\n <Balloon id=\"a11y-balloon\" type=\"primary\" autoFocus trigger={innerButton} triggerType=\"click\">\n <Balloon id=\"inner-a11y-balloon\" autoFocus trigger={<Button type=\"primary\">Fill in sub-form</Button>} popupContainer={(trigger) => trigger.parentNode} triggerType=\"click\">\n please input your age:\n <Input placeholder=\"Age\" size=\"small\" label=\"Age :\" id=\"balloon-input-2\" /><br /><br />\n </Balloon>\n <br />\n please input your name:\n <Input placeholder=\"Name\" size=\"small\" label=\"Name :\" id=\"balloon-input-3\" /><br /><br />\n </Balloon>\n\n \n\n <Tooltip trigger={triggerTooltip} id=\"aria-tooltip\">\n <p>This is content for tooltip.</p>\n </Tooltip>\n </div>\n);\n\nReactDOM.render(<App />, mountNode);
.container.nested {\n margin-left: 100px;\n margin-bottom: 50px;\n}
弹层id, 传入值才会支持无障碍。
\n","order":"8"},"codes":{"jsx":"\nimport { Button, Balloon, Input } from '@alifd/next';\nimport moment from 'moment';\n\nconst { Tooltip } = Balloon;\nconst innerButton = ;\nconst triggerTooltip = ;\n\nconst App = () => (\nThis is content for tooltip.
\nThis is content for tooltip.
\n\nimport { Button, Balloon, Input } from '@alifd/next';\nimport moment from 'moment';\n\nconst { Tooltip } = Balloon;\nconst innerButton = <Button className=\"btrigger\">Fill in form</Button>;\nconst triggerTooltip = <Button style={{margin: '5px'}}>show tooltip</Button>;\n\nconst App = () => (\n <div className=\"container nested\">\n <Balloon id=\"inner-a11y-balloon-1\" autoFocus trigger={<Button type=\"primary\">Fill in sub-form</Button>} popupContainer={(trigger) => trigger.parentNode} triggerType=\"click\">\n please input your age:\n <Input placeholder=\"Age\" size=\"small\" label=\"Age :\" id=\"balloon-input-1\" /><br /><br />\n </Balloon>\n\n \n\n <Balloon id=\"a11y-balloon\" type=\"primary\" autoFocus trigger={innerButton} triggerType=\"click\">\n <Balloon id=\"inner-a11y-balloon\" autoFocus trigger={<Button type=\"primary\">Fill in sub-form</Button>} popupContainer={(trigger) => trigger.parentNode} triggerType=\"click\">\n please input your age:\n <Input placeholder=\"Age\" size=\"small\" label=\"Age :\" id=\"balloon-input-2\" /><br /><br />\n </Balloon>\n <br />\n please input your name:\n <Input placeholder=\"Name\" size=\"small\" label=\"Name :\" id=\"balloon-input-3\" /><br /><br />\n </Balloon>\n\n \n\n <Tooltip trigger={triggerTooltip} id=\"aria-tooltip\">\n <p>This is content for tooltip.</p>\n </Tooltip>\n </div>\n);\n\nReactDOM.render(<App />, mountNode);
.container.nested {\n margin-left: 100px;\n margin-bottom: 50px;\n}
There are 12 options for align
\n","order":"3"},"codes":{"jsx":"import { Button, Balloon } from '@alifd/next';\n\nconst top = ;\nconst right = ;\nconst bottom = ;\nconst left = ;\nconst topLeft = ;\nconst topRight = ;\nconst rightTop = ;\nconst rightBottom = ;\nconst bottomLeft = ;\nconst bottomRight = ;\nconst leftTop = ;\nconst leftBottom = ;\n\nconst Content = () => (\n\n balloon content\n
\n\n balloon content\n
\nimport { Button, Balloon } from '@alifd/next';\n\nconst top = <Button id=\"top\" style={{margin: '5px'}} className=\"btrigger\">top</Button>;\nconst right = <Button id=\"right\" style={{margin: '5px'}} className=\"btrigger\">right</Button>;\nconst bottom = <Button id=\"bottom\" style={{margin: '5px'}} className=\"btrigger\">bottom</Button>;\nconst left = <Button id=\"left\" style={{margin: '5px'}} className=\"btrigger\">left</Button>;\nconst topLeft = <Button id=\"topLeft\" style={{margin: '5px'}} className=\"btrigger\">top left</Button>;\nconst topRight = <Button id=\"topRight\" style={{margin: '5px'}} className=\"btrigger\">top right</Button>;\nconst rightTop = <Button id=\"rightTop\" style={{margin: '5px'}} className=\"btrigger\">right top</Button>;\nconst rightBottom = <Button id=\"rightBottom\" style={{margin: '5px'}} className=\"btrigger\">right bottom</Button>;\nconst bottomLeft = <Button id=\"bottomLeft\" style={{margin: '5px'}} className=\"btrigger\">bottom left</Button>;\nconst bottomRight = <Button id=\"bottomRight\" style={{margin: '5px'}} className=\"btrigger\">bottom right</Button>;\nconst leftTop = <Button id=\"leftTop\" style={{margin: '5px'}} className=\"btrigger\">left top</Button>;\nconst leftBottom = <Button id=\"leftBottom\" style={{margin: '5px'}} className=\"btrigger\">left bottom</Button>;\n\nconst Content = () => (\n <div>\n <h4 style={{marginTop: 0}}>balloon title</h4>\n <hr/>\n <p>\n balloon content\n </p>\n </div>\n);\n\nconst App = () => (\n <div style={{paddingLeft: 320, paddingTop: 100}}>\n <div style={{marginLeft: 75}}>\n <Balloon trigger={topLeft} align=\"tl\" alignEdge triggerType=\"click\" style={{width: 300}}>\n <Content/>\n </Balloon>\n <Balloon trigger={top} align=\"t\" alignEdge triggerType=\"click\" style={{width: 300}}>\n <Content/>\n </Balloon>\n <Balloon trigger={topRight} align=\"tr\" alignEdge triggerType=\"click\" style={{width: 300}}>\n <Content/>\n </Balloon>\n </div>\n <div style={{width: 80, float: 'left'}}>\n <Balloon trigger={leftTop} align=\"lt\" alignEdge triggerType=\"click\" style={{width: 300}}>\n <Content/>\n </Balloon>\n <Balloon trigger={left} align=\"l\" alignEdge triggerType=\"click\" style={{width: 300}}>\n <Content/>\n </Balloon>\n <Balloon trigger={leftBottom} align=\"lb\" alignEdge triggerType=\"click\" style={{width: 300}}>\n <Content/>\n </Balloon>\n </div>\n <div style={{width: 80, marginLeft: 290}}>\n <Balloon trigger={rightTop} align=\"rt\" alignEdge triggerType=\"click\" style={{width: 300}}>\n <Content/>\n </Balloon>\n <Balloon trigger={right} align=\"r\" alignEdge triggerType=\"click\" style={{width: 300}}>\n <Content/>\n </Balloon>\n <Balloon trigger={rightBottom} align=\"rb\" alignEdge triggerType=\"click\" style={{width: 300}}>\n <Content/>\n </Balloon>\n </div>\n <div style={{marginLeft: 80, clear: 'both'}}>\n <Balloon trigger={bottomLeft} align=\"bl\" alignEdge triggerType=\"click\" style={{width: 300}}>\n <Content/>\n </Balloon>\n <Balloon trigger={bottom} align=\"b\" alignEdge triggerType=\"click\" style={{width: 300}}>\n <Content/>\n </Balloon>\n <Balloon trigger={bottomRight} align=\"br\" alignEdge triggerType=\"click\" style={{width: 300}}>\n <Content/>\n </Balloon>\n </div>\n </div>\n);\n\nReactDOM.render(<App />, mountNode);\n
位置有十二个方向。
\n","order":"3"},"codes":{"jsx":"import { Button, Balloon } from '@alifd/next';\n\nconst top = ;\nconst right = ;\nconst bottom = ;\nconst left = ;\nconst topLeft = ;\nconst topRight = ;\nconst rightTop = ;\nconst rightBottom = ;\nconst bottomLeft = ;\nconst bottomRight = ;\nconst leftTop = ;\nconst leftBottom = ;\n\nconst Content = () => (\n\n balloon content\n
\n\n balloon content\n
\nimport { Button, Balloon } from '@alifd/next';\n\nconst top = <Button id=\"top\" style={{margin: '5px'}} className=\"btrigger\">top</Button>;\nconst right = <Button id=\"right\" style={{margin: '5px'}} className=\"btrigger\">right</Button>;\nconst bottom = <Button id=\"bottom\" style={{margin: '5px'}} className=\"btrigger\">bottom</Button>;\nconst left = <Button id=\"left\" style={{margin: '5px'}} className=\"btrigger\">left</Button>;\nconst topLeft = <Button id=\"topLeft\" style={{margin: '5px'}} className=\"btrigger\">top left</Button>;\nconst topRight = <Button id=\"topRight\" style={{margin: '5px'}} className=\"btrigger\">top right</Button>;\nconst rightTop = <Button id=\"rightTop\" style={{margin: '5px'}} className=\"btrigger\">right top</Button>;\nconst rightBottom = <Button id=\"rightBottom\" style={{margin: '5px'}} className=\"btrigger\">right bottom</Button>;\nconst bottomLeft = <Button id=\"bottomLeft\" style={{margin: '5px'}} className=\"btrigger\">bottom left</Button>;\nconst bottomRight = <Button id=\"bottomRight\" style={{margin: '5px'}} className=\"btrigger\">bottom right</Button>;\nconst leftTop = <Button id=\"leftTop\" style={{margin: '5px'}} className=\"btrigger\">left top</Button>;\nconst leftBottom = <Button id=\"leftBottom\" style={{margin: '5px'}} className=\"btrigger\">left bottom</Button>;\n\nconst Content = () => (\n <div>\n <h4 style={{marginTop: 0}}>balloon title</h4>\n <hr/>\n <p>\n balloon content\n </p>\n </div>\n);\n\nconst App = () => (\n <div style={{paddingLeft: 320, paddingTop: 100}}>\n <div style={{marginLeft: 75}}>\n <Balloon trigger={topLeft} align=\"tl\" alignEdge triggerType=\"click\" style={{width: 300}}>\n <Content/>\n </Balloon>\n <Balloon trigger={top} align=\"t\" alignEdge triggerType=\"click\" style={{width: 300}}>\n <Content/>\n </Balloon>\n <Balloon trigger={topRight} align=\"tr\" alignEdge triggerType=\"click\" style={{width: 300}}>\n <Content/>\n </Balloon>\n </div>\n <div style={{width: 80, float: 'left'}}>\n <Balloon trigger={leftTop} align=\"lt\" alignEdge triggerType=\"click\" style={{width: 300}}>\n <Content/>\n </Balloon>\n <Balloon trigger={left} align=\"l\" alignEdge triggerType=\"click\" style={{width: 300}}>\n <Content/>\n </Balloon>\n <Balloon trigger={leftBottom} align=\"lb\" alignEdge triggerType=\"click\" style={{width: 300}}>\n <Content/>\n </Balloon>\n </div>\n <div style={{width: 80, marginLeft: 290}}>\n <Balloon trigger={rightTop} align=\"rt\" alignEdge triggerType=\"click\" style={{width: 300}}>\n <Content/>\n </Balloon>\n <Balloon trigger={right} align=\"r\" alignEdge triggerType=\"click\" style={{width: 300}}>\n <Content/>\n </Balloon>\n <Balloon trigger={rightBottom} align=\"rb\" alignEdge triggerType=\"click\" style={{width: 300}}>\n <Content/>\n </Balloon>\n </div>\n <div style={{marginLeft: 80, clear: 'both'}}>\n <Balloon trigger={bottomLeft} align=\"bl\" alignEdge triggerType=\"click\" style={{width: 300}}>\n <Content/>\n </Balloon>\n <Balloon trigger={bottom} align=\"b\" alignEdge triggerType=\"click\" style={{width: 300}}>\n <Content/>\n </Balloon>\n <Balloon trigger={bottomRight} align=\"br\" alignEdge triggerType=\"click\" style={{width: 300}}>\n <Content/>\n </Balloon>\n </div>\n </div>\n);\n\nReactDOM.render(<App />, mountNode);\n
Basic usage.
\n","order":"0"},"codes":{"jsx":"import { Button, Balloon } from '@alifd/next';\n\n\n\nconst defaultTrigger = ;\nconst disabledTrigger = ;\nconst primary = ;\n\nconst Demo = () => (\nimport { Button, Balloon } from '@alifd/next';\n\n\n\nconst defaultTrigger = <Button className=\"btrigger\" style={{margin: '5px'}}>default style</Button>;\nconst disabledTrigger = <Button disabled className=\"btrigger\" style={{margin: '5px'}}>default style</Button>;\nconst primary = <Button className=\"btrigger\" style={{margin: '5px'}}>primary style</Button>;\n\nconst Demo = () => (\n <div className=\"container\">\n <Balloon trigger={defaultTrigger} closable={false}>\n default\n </Balloon>\n <Balloon type=\"primary\" trigger={primary} triggerType=\"click\">\n primary\n </Balloon>\n <Balloon trigger={disabledTrigger} closable={false}>\n disabeled default\n </Balloon>\n </div>\n);\n\nReactDOM.render(<Demo />, mountNode);\n
最简单的用法。
\n","order":"0"},"codes":{"jsx":"import { Button, Balloon } from '@alifd/next';\n\n\n\nconst defaultTrigger = ;\nconst disabledTrigger = ;\nconst primary = ;\n\nconst Demo = () => (\nimport { Button, Balloon } from '@alifd/next';\n\n\n\nconst defaultTrigger = <Button className=\"btrigger\" style={{margin: '5px'}}>default style</Button>;\nconst disabledTrigger = <Button disabled className=\"btrigger\" style={{margin: '5px'}}>default style</Button>;\nconst primary = <Button className=\"btrigger\" style={{margin: '5px'}}>primary style</Button>;\n\nconst Demo = () => (\n <div className=\"container\">\n <Balloon trigger={defaultTrigger} closable={false}>\n default\n </Balloon>\n <Balloon type=\"primary\" trigger={primary} triggerType=\"click\">\n primary\n </Balloon>\n <Balloon trigger={disabledTrigger} closable={false}>\n disabeled default\n </Balloon>\n </div>\n);\n\nReactDOM.render(<Demo />, mountNode);\n
Use 'visible' to control whether the popup should be displayed.
\n","order":"4"},"codes":{"jsx":"import { Button, Balloon } from '@alifd/next';\n\nclass App extends React.Component {\n constructor(props) {\n super(props);\n this.state = {\n visible: false\n };\n }\n\n hide() {\n this.setState({\n visible: false\n });\n }\n\n // onVisibleChange callback will be triggered when visible changes.\n // For example, for click type, it'll be triggered when clicking the button and later the other areas;\n // for hover type, it'll be triggered when mouse enter and mouse leave\n handleVisibleChange(visible) {\n this.setState({visible});\n }\n\n onClose() {\n console.log('onClose doing!');\n }\n\n afterClose() {\n console.log('afterClose doing!');\n }\n render() {\n const visibleTrigger = ;\n const clickTrigger = ;\n\n const content = ();\n return (\nimport { Button, Balloon } from '@alifd/next';\n\nclass App extends React.Component {\n constructor(props) {\n super(props);\n this.state = {\n visible: false\n };\n }\n\n hide() {\n this.setState({\n visible: false\n });\n }\n\n // onVisibleChange callback will be triggered when visible changes.\n // For example, for click type, it'll be triggered when clicking the button and later the other areas;\n // for hover type, it'll be triggered when mouse enter and mouse leave\n handleVisibleChange(visible) {\n this.setState({visible});\n }\n\n onClose() {\n console.log('onClose doing!');\n }\n\n afterClose() {\n console.log('afterClose doing!');\n }\n render() {\n const visibleTrigger = <Button type=\"primary\" style={{margin: '5px'}}>click to popup the card</Button>;\n const clickTrigger = <Button type=\"primary\" style={{margin: '5px'}}>hover to popup the card</Button>;\n\n const content = (<div>\n click the button<br/>\n <a style={{right: 0}} id=\"confirmBtn\" onClick={this.hide.bind(this)}>confirm</a>\n <a style={{marginLeft: '4px'}} id=\"cancelBtn\" onClick={this.hide.bind(this)}>cancel</a>\n </div>);\n return (\n <div>\n <Balloon trigger={visibleTrigger}\n triggerType=\"click\"\n visible={this.state.visible}\n onVisibleChange={this.handleVisibleChange.bind(this)}\n >\n {content}\n </Balloon>\n <Balloon trigger={clickTrigger}\n triggerType=\"hover\"\n onClose={this.onClose.bind(this)}\n afterClose={this.afterClose.bind(this)}>\n {content}\n </Balloon>\n </div>\n );\n }\n}\n\nReactDOM.render(<App />, mountNode);\n
使用 visible
,属性控制浮层显示, 使 balloon 变为受限组件。
import { Button, Balloon } from '@alifd/next';\n\nclass App extends React.Component {\n constructor(props) {\n super(props);\n this.state = {\n visible: false\n };\n }\n\n hide() {\n this.setState({\n visible: false\n });\n }\n\n // onVisibleChange callback will be triggered when visible changes.\n // For example, for click type, it'll be triggered when clicking the button and later the other areas;\n // for hover type, it'll be triggered when mouse enter and mouse leave\n handleVisibleChange(visible) {\n this.setState({visible});\n }\n\n onClose() {\n console.log('onClose doing!');\n }\n\n afterClose() {\n console.log('afterClose doing!');\n }\n render() {\n const visibleTrigger = <Button type=\"primary\" style={{margin: '5px'}}>click to popup the card</Button>;\n const clickTrigger = <Button type=\"primary\" style={{margin: '5px'}}>hover to popup the card</Button>;\n\n const content = (<div>\n click the button<br/>\n <a style={{right: 0}} id=\"confirmBtn\" onClick={this.hide.bind(this)}>confirm</a>\n <a style={{marginLeft: '4px'}} id=\"cancelBtn\" onClick={this.hide.bind(this)}>cancel</a>\n </div>);\n return (\n <div>\n <Balloon trigger={visibleTrigger}\n triggerType=\"click\"\n visible={this.state.visible}\n onVisibleChange={this.handleVisibleChange.bind(this)}\n >\n {content}\n </Balloon>\n <Balloon trigger={clickTrigger}\n triggerType=\"hover\"\n onClose={this.onClose.bind(this)}\n afterClose={this.afterClose.bind(this)}>\n {content}\n </Balloon>\n </div>\n );\n }\n}\n\nReactDOM.render(<App />, mountNode);\n
When popup is nested in another popup, say DatePicker is nested in Balloon, use followTrigger
to avoid the unexpected Balloon's closing.
import { Button, Balloon, DatePicker, Select } from '@alifd/next';\nimport moment from 'moment';\n\nconst showSelect = <Button className=\"btrigger\">Show Select</Button>;\nconst showDatePicker = <Button className=\"btrigger\">Show DatePicker</Button>;\nconst innerButton = <Button className=\"btrigger\">Show Inner Balloon</Button>;\nconst dateValue = moment('2018-01-01', 'YYYY-MM-DD', true);\n\nconst App = () => (\n <div className=\"container nested\">\n <Balloon type=\"primary\" autoFocus trigger={showSelect} closable={false} triggerType=\"click\">\n <Select dataSource={['apple', 'banana', 'orange']} followTrigger />\n </Balloon>\n \n <Balloon type=\"primary\" autoFocus trigger={showDatePicker} closable={false} triggerType=\"click\">\n <DatePicker defaultValue={dateValue} followTrigger />\n </Balloon>\n \n <Balloon type=\"primary\" autoFocus trigger={innerButton} closable={false} triggerType=\"click\">\n <Balloon trigger={<Button type=\"primary\">please click</Button>} followTrigger triggerType=\"click\">\n nesting balloon content\n </Balloon>\n </Balloon>\n </div>\n);\n\nReactDOM.render(<App />, mountNode);\n
\n.container.nested {\n margin-bottom: 50px;\n}\n
浮层中如果又有浮层,比如在Balloon
中有DatePicker/Select
的浮层, DatePicker
选择时,Balloon
浮层也会关闭。可以用 followTrigger
解决。
import { Button, Balloon, DatePicker, Select } from '@alifd/next';\nimport moment from 'moment';\n\nconst showSelect = <Button className=\"btrigger\">Show Select</Button>;\nconst showDatePicker = <Button className=\"btrigger\">Show DatePicker</Button>;\nconst innerButton = <Button className=\"btrigger\">Show Inner Balloon</Button>;\nconst dateValue = moment('2018-01-01', 'YYYY-MM-DD', true);\n\nconst App = () => (\n <div className=\"container nested\">\n <Balloon type=\"primary\" autoFocus trigger={showSelect} closable={false} triggerType=\"click\">\n <Select dataSource={['apple', 'banana', 'orange']} followTrigger />\n </Balloon>\n \n <Balloon type=\"primary\" autoFocus trigger={showDatePicker} closable={false} triggerType=\"click\">\n <DatePicker defaultValue={dateValue} followTrigger />\n </Balloon>\n \n <Balloon type=\"primary\" autoFocus trigger={innerButton} closable={false} triggerType=\"click\">\n <Balloon trigger={<Button type=\"primary\">please click</Button>} followTrigger triggerType=\"click\">\n nesting balloon content\n </Balloon>\n </Balloon>\n </div>\n);\n\nReactDOM.render(<App />, mountNode);\n
\n.container.nested {\n margin-bottom: 50px;\n}\n
When popup is nested in another popup, say DatePicker is nested in Balloon, use safeNode to avoid the unexpected Balloon's closing.
\n","order":"5"},"codes":{"jsx":"import { Button, Balloon } from '@alifd/next';\n\nclass App extends React.Component {\n constructor(props) {\n super(props);\n this.state = {\n visible: false\n };\n }\n\n // triggered every time visible becomes false\n onClose() {\n console.log('onClose doing!');\n }\n\n onClick() {\n this.setState({visible: true});\n }\n\n render() {\n const visibleTrigger = ;\n const content = (import { Button, Balloon } from '@alifd/next';\n\nclass App extends React.Component {\n constructor(props) {\n super(props);\n this.state = {\n visible: false\n };\n }\n\n // triggered every time visible becomes false\n onClose() {\n console.log('onClose doing!');\n }\n\n onClick() {\n this.setState({visible: true});\n }\n\n render() {\n const visibleTrigger = <Button onClick={this.onClick.bind(this)} type=\"primary\">click to pupup the card</Button>;\n const content = (<div>content</div>);\n\n return (\n <div style={{marginBottom: '100px'}}>\n <Balloon trigger={visibleTrigger}\n triggerType=\"click\"\n visible={this.state.visible}\n onClose={this.onClose.bind(this)} >\n {content}\n </Balloon>\n </div>\n );\n }\n}\n\nReactDOM.render(<App />, mountNode);\n
使用 visible
,属性控制浮层显示, 使balloon变为受限组件。
import { Button, Balloon } from '@alifd/next';\n\nclass App extends React.Component {\n constructor(props) {\n super(props);\n this.state = {\n visible: false\n };\n }\n\n // triggered every time visible becomes false\n onClose() {\n console.log('onClose doing!');\n }\n\n onClick() {\n this.setState({visible: true});\n }\n\n render() {\n const visibleTrigger = <Button onClick={this.onClick.bind(this)} type=\"primary\">click to pupup the card</Button>;\n const content = (<div>content</div>);\n\n return (\n <div style={{marginBottom: '100px'}}>\n <Balloon trigger={visibleTrigger}\n triggerType=\"click\"\n visible={this.state.visible}\n onClose={this.onClose.bind(this)} >\n {content}\n </Balloon>\n </div>\n );\n }\n}\n\nReactDOM.render(<App />, mountNode);\n
Simplified Balloon, which can only set align, trigger and children, and triggered by hovering.
\n","order":"7"},"codes":{"jsx":"import { Button, Balloon } from '@alifd/next';\n\nconst Tooltip = Balloon.Tooltip;\n\nconst top = ;\nconst right = ;\nconst bottom = ;\nconst left = ;\nconst topLeft = ;\nconst topRight = ;\nconst rightTop = ;\nconst rightBottom = ;\nconst bottomLeft = ;\nconst bottomRight = ;\nconst leftTop = ;\nconst leftBottom = ;\n\nconst App = () => (\nimport { Button, Balloon } from '@alifd/next';\n\nconst Tooltip = Balloon.Tooltip;\n\nconst top = <Button style={{margin: '5px'}} id=\"top\" className=\"btrigger\">top</Button>;\nconst right = <Button style={{margin: '5px'}}id=\"right\" className=\"btrigger\">right</Button>;\nconst bottom = <Button style={{margin: '5px'}} id=\"bottom\" className=\"btrigger\">bottom</Button>;\nconst left = <Button style={{margin: '5px'}} id=\"left\" className=\"btrigger\">left</Button>;\nconst topLeft = <Button style={{margin: '5px'}} id=\"topLeft\" className=\"btrigger\">top left</Button>;\nconst topRight = <Button style={{margin: '5px'}} id=\"topRight\" className=\"btrigger\">top right</Button>;\nconst rightTop = <Button style={{margin: '5px'}} id=\"rightTop\" className=\"btrigger\">right top</Button>;\nconst rightBottom = <Button style={{margin: '5px'}} id=\"rightBottom\" className=\"btrigger\">right bottom</Button>;\nconst bottomLeft = <Button style={{margin: '5px'}} id=\"bottomLeft\" className=\"btrigger\">bottom left</Button>;\nconst bottomRight = <Button style={{margin: '5px'}} id=\"bottomRight\" className=\"btrigger\">bottom right</Button>;\nconst leftTop = <Button style={{margin: '5px'}} id=\"leftTop\" className=\"btrigger\">left top</Button>;\nconst leftBottom = <Button style={{margin: '5px'}} id=\"leftBottom\" className=\"btrigger\">left bottom</Button>;\n\nconst App = () => (\n <div style={{paddingLeft: 220, paddingTop: 100}}>\n <div style={{marginLeft: 75}}>\n <Tooltip trigger={topLeft} align=\"tl\">text text</Tooltip>\n <Tooltip trigger={top} align=\"t\">text text</Tooltip>\n <Tooltip trigger={topRight} align=\"tr\">text text</Tooltip>\n </div>\n <div style={{width: 80, float: 'left'}}>\n <Tooltip trigger={leftTop} align=\"lt\">text text</Tooltip>\n <Tooltip trigger={left} align=\"l\">text text</Tooltip>\n <Tooltip trigger={leftBottom} align=\"lb\">text text</Tooltip>\n </div>\n <div style={{width: 80, marginLeft: 290}}>\n <Tooltip trigger={rightTop} align=\"rt\">text text</Tooltip>\n <Tooltip trigger={right} align=\"r\">text text</Tooltip>\n <Tooltip trigger={rightBottom} align=\"rb\">text text</Tooltip>\n </div>\n <div style={{marginLeft: 80, clear: 'both'}}>\n <Tooltip trigger={bottomLeft} align=\"bl\">text text</Tooltip>\n <Tooltip trigger={bottom} align=\"b\">text text</Tooltip>\n <Tooltip trigger={bottomRight} align=\"br\">text text</Tooltip>\n </div>\n </div>\n\n);\n\nReactDOM.render(<App />, mountNode);\n
.code-box-demo .sui-btn {\n margin-right: 1em;\n margin-bottom: 1em;\n}
简化的Balloon, 只能设置align, trigger和children, 触发条件是hover.
\n","order":"7"},"codes":{"jsx":"import { Button, Balloon } from '@alifd/next';\n\nconst Tooltip = Balloon.Tooltip;\n\nconst top = ;\nconst right = ;\nconst bottom = ;\nconst left = ;\nconst topLeft = ;\nconst topRight = ;\nconst rightTop = ;\nconst rightBottom = ;\nconst bottomLeft = ;\nconst bottomRight = ;\nconst leftTop = ;\nconst leftBottom = ;\n\nconst App = () => (\nimport { Button, Balloon } from '@alifd/next';\n\nconst Tooltip = Balloon.Tooltip;\n\nconst top = <Button style={{margin: '5px'}} id=\"top\" className=\"btrigger\">top</Button>;\nconst right = <Button style={{margin: '5px'}}id=\"right\" className=\"btrigger\">right</Button>;\nconst bottom = <Button style={{margin: '5px'}} id=\"bottom\" className=\"btrigger\">bottom</Button>;\nconst left = <Button style={{margin: '5px'}} id=\"left\" className=\"btrigger\">left</Button>;\nconst topLeft = <Button style={{margin: '5px'}} id=\"topLeft\" className=\"btrigger\">top left</Button>;\nconst topRight = <Button style={{margin: '5px'}} id=\"topRight\" className=\"btrigger\">top right</Button>;\nconst rightTop = <Button style={{margin: '5px'}} id=\"rightTop\" className=\"btrigger\">right top</Button>;\nconst rightBottom = <Button style={{margin: '5px'}} id=\"rightBottom\" className=\"btrigger\">right bottom</Button>;\nconst bottomLeft = <Button style={{margin: '5px'}} id=\"bottomLeft\" className=\"btrigger\">bottom left</Button>;\nconst bottomRight = <Button style={{margin: '5px'}} id=\"bottomRight\" className=\"btrigger\">bottom right</Button>;\nconst leftTop = <Button style={{margin: '5px'}} id=\"leftTop\" className=\"btrigger\">left top</Button>;\nconst leftBottom = <Button style={{margin: '5px'}} id=\"leftBottom\" className=\"btrigger\">left bottom</Button>;\n\nconst App = () => (\n <div style={{paddingLeft: 220, paddingTop: 100}}>\n <div style={{marginLeft: 75}}>\n <Tooltip trigger={topLeft} align=\"tl\">text text</Tooltip>\n <Tooltip trigger={top} align=\"t\">text text</Tooltip>\n <Tooltip trigger={topRight} align=\"tr\">text text</Tooltip>\n </div>\n <div style={{width: 80, float: 'left'}}>\n <Tooltip trigger={leftTop} align=\"lt\">text text</Tooltip>\n <Tooltip trigger={left} align=\"l\">text text</Tooltip>\n <Tooltip trigger={leftBottom} align=\"lb\">text text</Tooltip>\n </div>\n <div style={{width: 80, marginLeft: 290}}>\n <Tooltip trigger={rightTop} align=\"rt\">text text</Tooltip>\n <Tooltip trigger={right} align=\"r\">text text</Tooltip>\n <Tooltip trigger={rightBottom} align=\"rb\">text text</Tooltip>\n </div>\n <div style={{marginLeft: 80, clear: 'both'}}>\n <Tooltip trigger={bottomLeft} align=\"bl\">text text</Tooltip>\n <Tooltip trigger={bottom} align=\"b\">text text</Tooltip>\n <Tooltip trigger={bottomRight} align=\"br\">text text</Tooltip>\n </div>\n </div>\n\n);\n\nReactDOM.render(<App />, mountNode);\n
.code-box-demo .sui-btn {\n margin-right: 1em;\n margin-bottom: 1em;\n}
Hover, focus and click.
\n","order":"1"},"codes":{"jsx":"import { Button, Balloon, Input } from '@alifd/next';\n\nconst content = (content
content
import { Button, Balloon, Input } from '@alifd/next';\n\nconst content = (<div><p>content</p></div>);\nconst MoveTarget = <Button style={{margin: '5px'}}>hover</Button>;\nconst ClickTarget = <Button style={{margin: '5px'}}>click</Button>;\nconst FocusTarget = <Button style={{margin: '5px'}}>focus</Button>;\n\nconst HoverInputTarget = <Input placeholder=\"hover\" style={{marginRight: '20px'}}/>;\nconst ClickInputTarget = <Input placeholder=\"click\" style={{marginRight: '20px'}}/>;\nconst FocusInputTarget = <Input placeholder=\"focus\" />;\n\nconst App = () => (\n <div>\n <Balloon trigger={MoveTarget} triggerType=\"hover\">\n {content}\n </Balloon>\n\n <Balloon trigger={ClickTarget} triggerType=\"click\">\n {content}\n </Balloon>\n\n <Balloon trigger={FocusTarget} triggerType=\"focus\">\n {content}\n </Balloon>\n\n <br/>\n <br/>\n\n <Balloon trigger={HoverInputTarget} triggerType=\"hover\">\n {content}\n </Balloon>\n <Balloon trigger={ClickInputTarget} triggerType=\"click\">\n {content}\n </Balloon>\n <Balloon trigger={FocusInputTarget} triggerType=\"focus\">\n {content}\n </Balloon>\n </div>\n);\n\nReactDOM.render(<App />, mountNode);\n
鼠标移入、聚集、点击。
\n","order":"1"},"codes":{"jsx":"import { Button, Balloon, Input } from '@alifd/next';\n\nconst content = (content
content
import { Button, Balloon, Input } from '@alifd/next';\n\nconst content = (<div><p>content</p></div>);\nconst MoveTarget = <Button style={{margin: '5px'}}>hover</Button>;\nconst ClickTarget = <Button style={{margin: '5px'}}>click</Button>;\nconst FocusTarget = <Button style={{margin: '5px'}}>focus</Button>;\n\nconst HoverInputTarget = <Input placeholder=\"hover\" style={{marginRight: '20px'}}/>;\nconst ClickInputTarget = <Input placeholder=\"click\" style={{marginRight: '20px'}}/>;\nconst FocusInputTarget = <Input placeholder=\"focus\" />;\n\nconst App = () => (\n <div>\n <Balloon trigger={MoveTarget} triggerType=\"hover\">\n {content}\n </Balloon>\n\n <Balloon trigger={ClickTarget} triggerType=\"click\">\n {content}\n </Balloon>\n\n <Balloon trigger={FocusTarget} triggerType=\"focus\">\n {content}\n </Balloon>\n\n <br/>\n <br/>\n\n <Balloon trigger={HoverInputTarget} triggerType=\"hover\">\n {content}\n </Balloon>\n <Balloon trigger={ClickInputTarget} triggerType=\"click\">\n {content}\n </Balloon>\n <Balloon trigger={FocusInputTarget} triggerType=\"focus\">\n {content}\n </Balloon>\n </div>\n);\n\nReactDOM.render(<App />, mountNode);\n
<Tooltip>
for simple tip, <Balloon triggerType="click">
for complex usage(e.g.nested with form). Don't use triggerType="focus", it's for Component internal use only.Param | \nDescription | \nType | \nDefault Value | \n
---|---|---|---|
type | \ntype of style option: 'normal', 'primary' | \nEnum | \n'normal' | \n
children | \ncontent of popup layer | \nany | \n- | \n
visible | \nvisible state of popup | \nBoolean | \n- | \n
defaultVisible | \ndefault visible state of popup | \nBoolean | \nfalse | \n
onVisibleChange | \ncallback when visible state changes signature: Function(visible: Boolean) => void parameter: visible: {Boolean} whether to show the popup | \nFunction | \nfunc.noop | \n
alignEdge | \nwhether align to the edge | \nBoolean | \nfalse | \n
closable | \nwhether to show the close button | \nBoolean | \ntrue | \n
align | \nposition of popup relative to the trigger option: 't'(top) 'r'(right) 'b'(bottom) 'l'(left) 'tl'(top left) 'tr'(top right) 'bl'(bottom left) 'br'(bottom right) 'lt'(left top) 'lb'(left bottom) 'rt'(right top) 'rb'(right bottom) or their combinations | \nEnum | \n'b' | \n
offset | \nextra adjustment for trigger element. e.g. [hoz, ver] means move to right ${hoz}px (to left in RTL mode), to bottom ${ver}px | \nArray | \n[0, 0] | \n
trigger | \ntrigger of the popup | \nany | \n<span></span> | \n
triggerType | \nhow to trigger the popup. type unit: 'hover' 'click' e.g.['hover', 'click'] 'click' | \nString/Array | \n'hover' | \n
onClose | \ncallback triggered when visible becomes false signature: Function() => void | \nFunction | \nfunc.noop | \n
needAdjust | \nwhether to adjust the position automatically | \nBoolean | \nfalse | \n
delay | \nhow long should the popup be delayed after triggered in milliseconds | \nNumber | \n- | \n
afterClose | \ncallback triggered when the popup is closed or the animation ends signature: Function() => void | \nFunction | \nfunc.noop | \n
shouldUpdatePosition | \nwhether to update the position of popup after the content changes | \nBoolean | \n- | \n
autoFocus | \nwhether to focus on the first element of popup on appearing | \nBoolean | \nfalse | \n
safeNode | \nWhen triggetType is 'click', the popup will be closed if any area other than itself is clicked. safeNode is used to define the node which doesn't trigger the close action. It can be either dom or dom id | \nString | \nundefined | \n
safeId | \nid of the safeNode, and should be used together with safeNode | \nString | \nnull | \n
animation | \nwhen should the animation be played | \nObject/Boolean | \n{ in: 'zoomIn', out: 'zoomOut' } | \n
cache | \nwhether to remove the popup when it's closed | \nBoolean | \nfalse | \n
popupContainer | \npopupContainer of the popup, being either dom id or a function to return the dom | \nString/Function | \n- | \n
popupStyle | \ncustom style of popup | \nObject | \n{} | \n
popupClassName | \ncustom className of popup | \nString | \n'' | \n
popupProps | \nprops of popup | \nObject | \n{} | \n
followTrigger | \nfollow Trigger or not | \nBoolean | \n- | \n
id | \nid of popup. only when you set value, balloon will support accessibility | \nString | \n- | \n
Param | \nDescription | \nType | \nDefault Value | \n
---|---|---|---|
children | \ncontent of tooltip | \nany | \n- | \n
align | \nposition of popup relative to the trigger option: 't'(top) 'r'(right) 'b'(bottom) 'l'(left) 'tl'(top left) 'tr'(top right) 'bl'(bottom left) 'br'(bottom right) 'lt'(left top) 'lb'(left bottom) 'rt'(right top) 'rb'(right bottom) or their combinations | \nEnum | \n'b' | \n
trigger | \ntrigger of the tooltip | \nany | \n<span></span> | \n
triggerType | \nhow to trigger the tooltip. type unit: 'hover' 'click' e.g.['hover', 'click'] 'click'. <Balloon triggerType="click"> for complex usage | \nString/Array | \n'hover' | \n
popupStyle | \ncustom style of popup | \nObject | \n- | \n
popupClassName | \ncustom className of popup | \nString | \n- | \n
popupProps | \nprops of popup | \nObject | \n- | \n
pure | \npure render or not | \nBoolean | \n- | \n
popupContainer | \npopupContainer of the popup, being either dom id or a function to return the dom | \nString/Function | \n- | \n
id | \nid of popup. only when you set value, balloon will support accessibility | \nString | \n- | \n
KeyBoard | \nDescripiton | \n
---|---|
SPACE | \nWhen triggerType=‘click’ , click will popup a prompt | \n
Enter | \nWhen triggerType=‘click’ , click will popup a prompt | \n
气泡组件
\n<Tooltip>
、复杂交互使用<Balloon triggerType="click">
。 triggerType="focus"作为辅助状态用于组件内部,请用户不要直接使用此值。参数 | \n说明 | \n类型 | \n默认值 | \n
---|---|---|---|
children | \n浮层的内容 | \nany | \n- | \n
type | \n样式类型 可选值: 'normal', 'primary' | \nEnum | \n'normal' | \n
visible | \n弹层当前显示的状态 | \nBoolean | \n- | \n
defaultVisible | \n弹层默认显示的状态 | \nBoolean | \nfalse | \n
onVisibleChange | \n弹层在显示和隐藏触发的事件 签名: Function(visible: Boolean, type: String) => void 参数: visible: {Boolean} 弹层是否隐藏和显示 type: {String} 触发弹层显示或隐藏的来源, closeClick 表示由自带的关闭按钮触发; fromTrigger 表示由trigger的点击触发; docClick 表示由document的点击触发 | \nFunction | \nfunc.noop | \n
alignEdge | \n弹出层对齐方式 | \nBoolean | \nfalse | \n
closable | \n是否显示关闭按钮 | \nBoolean | \ntrue | \n
align | \n弹出层位置 可选值: 't'(上) 'r'(右) 'b'(下) 'l'(左) 'tl'(上左) 'tr'(上右) 'bl'(下左) 'br'(下右) 'lt'(左上) 'lb'(左下) 'rt'(右上) 'rb'(右下 及其 两两组合) | \nEnum | \n'b' | \n
offset | \n弹层相对于trigger的定位的微调, 接收数组[hoz, ver], 表示弹层在 left / top 上的增量 e.g. [100, 100] 表示往右(RTL 模式下是往左) 、下分布偏移100px | \nArray | \n[0, 0] | \n
trigger | \n触发元素 | \nany | \n<span /> | \n
triggerType | \n触发行为 鼠标悬浮, 鼠标点击('hover','click')或者它们组成的数组,如 ['hover', 'click'], 强烈不建议使用'focus',若弹窗内容有复杂交互请使用click | \nString/Array | \n'hover' | \n
onClose | \n任何visible为false时会触发的事件 签名: Function() => void | \nFunction | \nfunc.noop | \n
needAdjust | \n是否进行自动位置调整 | \nBoolean | \nfalse | \n
delay | \n弹层在触发以后的延时显示, 单位毫秒 ms | \nNumber | \n- | \n
afterClose | \n浮层关闭后触发的事件, 如果有动画,则在动画结束后触发 签名: Function() => void | \nFunction | \nfunc.noop | \n
shouldUpdatePosition | \n强制更新定位信息 | \nBoolean | \n- | \n
autoFocus | \n弹层出现后是否自动focus到内部第一个元素 | \nBoolean | \ntrue | \n
safeNode | \n安全节点:对于triggetType为click的浮层,会在点击除了浮层外的其它区域时关闭浮层.safeNode用于添加不触发关闭的节点, 值可以是dom节点的id或者是节点的dom对象 | \nString | \nundefined | \n
safeId | \n用来指定safeNode节点的id,和safeNode配合使用 | \nString | \nnull | \n
animation | \n配置动画的播放方式 | \nObject/Boolean | \n{ in: 'zoomIn', out: 'zoomOut', } | \n
cache | \n弹层的dom节点关闭时是否删除 | \nBoolean | \nfalse | \n
popupContainer | \n指定浮层渲染的父节点, 可以为节点id的字符串,也可以返回节点的函数。 | \nString/Function | \n- | \n
popupStyle | \n弹层组件style,透传给Popup | \nObject | \n{} | \n
popupClassName | \n弹层组件className,透传给Popup | \nString | \n'' | \n
popupProps | \n弹层组件属性,透传给Popup | \nObject | \n{} | \n
followTrigger | \n是否跟随滚动 | \nBoolean | \n- | \n
id | \n弹层id, 传入值才会支持无障碍 | \nString | \n- | \n
参数 | \n说明 | \n类型 | \n默认值 | \n
---|---|---|---|
children | \ntooltip的内容 | \nany | \n- | \n
align | \n弹出层位置 可选值: 't'(上) 'r'(右) 'b'(下) 'l'(左) 'tl'(上左) 'tr'(上右) 'bl'(下左) 'br'(下右) 'lt'(左上) 'lb'(左下) 'rt'(右上) 'rb'(右下 及其 两两组合) | \nEnum | \n'b' | \n
trigger | \n触发元素 | \nany | \n<span /> | \n
triggerType | \n触发行为 鼠标悬浮, 鼠标点击('hover', 'click')或者它们组成的数组,如 ['hover', 'click'], 强烈不建议使用'focus',若有复杂交互,推荐使用triggerType为click的Balloon组件 | \nString/Array | \n'hover' | \n
popupStyle | \n弹层组件style,透传给Popup | \nObject | \n- | \n
popupClassName | \n弹层组件className,透传给Popup | \nString | \n- | \n
popupProps | \n弹层组件属性,透传给Popup | \nObject | \n- | \n
pure | \n是否pure render | \nBoolean | \n- | \n
popupContainer | \n指定浮层渲染的父节点, 可以为节点id的字符串,也可以返回节点的函数。 | \nString/Function | \n- | \n
followTrigger | \n是否跟随滚动 | \nBoolean | \n- | \n
id | \n弹层id, 传入值才会支持无障碍 | \nString | \n- | \n
按键 | \n说明 | \n
---|---|
SPACE | \n当triggerType=‘click’ 时,点击会弹出提示 | \n
Enter | \n当triggerType=‘click’ 时,点击会弹出提示 | \n
Use Breadcrumb.Item
to set the breadcrumb subnode, if its link
properity is set to be a <a />
node, otherwise it is a <span />
.
import { Breadcrumb } from '@alifd/next';\n\nReactDOM.render(\n <Breadcrumb>\n <Breadcrumb.Item link=\"javascript:void(0);\">Home</Breadcrumb.Item>\n <Breadcrumb.Item link=\"javascript:void(0);\">All Categories</Breadcrumb.Item>\n <Breadcrumb.Item link=\"javascript:void(0);\">Women’s Clothing</Breadcrumb.Item>\n <Breadcrumb.Item link=\"javascript:void(0);\">Blouses & Shirts</Breadcrumb.Item>\n <Breadcrumb.Item>\n T-shirts <b>78,999</b> Results\n </Breadcrumb.Item>\n </Breadcrumb>,\n mountNode);
使用 Breadcrumb.Item
来设置面包屑子节点,如果设置其 link
属性就是 <a />
节点,否则为 <span />
节点。
import { Breadcrumb } from '@alifd/next';\n\nReactDOM.render(\n <Breadcrumb>\n <Breadcrumb.Item link=\"javascript:void(0);\">Home</Breadcrumb.Item>\n <Breadcrumb.Item link=\"javascript:void(0);\">All Categories</Breadcrumb.Item>\n <Breadcrumb.Item link=\"javascript:void(0);\">Women’s Clothing</Breadcrumb.Item>\n <Breadcrumb.Item link=\"javascript:void(0);\">Blouses & Shirts</Breadcrumb.Item>\n <Breadcrumb.Item>\n T-shirts <b>78,999</b> Results\n </Breadcrumb.Item>\n </Breadcrumb>,\n mountNode);
import { Breadcrumb } from '@alifd/next';\n\nReactDOM.render(\n <Breadcrumb maxNode={5}>\n <Breadcrumb.Item link=\"javascript:void(0);\">Home 1</Breadcrumb.Item>\n <Breadcrumb.Item link=\"javascript:void(0);\">Whatever 2</Breadcrumb.Item>\n <Breadcrumb.Item link=\"javascript:void(0);\">All Categories 3</Breadcrumb.Item>\n <Breadcrumb.Item link=\"javascript:void(0);\">Women’s Clothing 4</Breadcrumb.Item>\n <Breadcrumb.Item link=\"javascript:void(0);\">Blouses & Shirts 5</Breadcrumb.Item>\n <Breadcrumb.Item>T-shirts 6</Breadcrumb.Item>\n </Breadcrumb>,\n mountNode);
当超过设置的最大个数的时候,显示省略号。
\n","order":"1"},"codes":{"jsx":"import { Breadcrumb } from '@alifd/next';\n\nReactDOM.render(\nimport { Breadcrumb } from '@alifd/next';\n\nReactDOM.render(\n <Breadcrumb maxNode={5}>\n <Breadcrumb.Item link=\"javascript:void(0);\">Home 1</Breadcrumb.Item>\n <Breadcrumb.Item link=\"javascript:void(0);\">Whatever 2</Breadcrumb.Item>\n <Breadcrumb.Item link=\"javascript:void(0);\">All Categories 3</Breadcrumb.Item>\n <Breadcrumb.Item link=\"javascript:void(0);\">Women’s Clothing 4</Breadcrumb.Item>\n <Breadcrumb.Item link=\"javascript:void(0);\">Blouses & Shirts 5</Breadcrumb.Item>\n <Breadcrumb.Item>T-shirts 6</Breadcrumb.Item>\n </Breadcrumb>,\n mountNode);
import { Breadcrumb } from '@alifd/next';\n\nReactDOM.render(\n <Breadcrumb separator=\"/\">\n <Breadcrumb.Item link=\"javascript:void(0);\">Home</Breadcrumb.Item>\n <Breadcrumb.Item link=\"javascript:void(0);\">All Categories</Breadcrumb.Item>\n <Breadcrumb.Item link=\"javascript:void(0);\">Women’s Clothing</Breadcrumb.Item>\n <Breadcrumb.Item link=\"javascript:void(0);\">Blouses & Shirts</Breadcrumb.Item>\n <Breadcrumb.Item>T-shirts</Breadcrumb.Item>\n </Breadcrumb>,\n mountNode);
也可以设置不同的分隔符。
\n","order":"2"},"codes":{"jsx":"import { Breadcrumb } from '@alifd/next';\n\nReactDOM.render(\nimport { Breadcrumb } from '@alifd/next';\n\nReactDOM.render(\n <Breadcrumb separator=\"/\">\n <Breadcrumb.Item link=\"javascript:void(0);\">Home</Breadcrumb.Item>\n <Breadcrumb.Item link=\"javascript:void(0);\">All Categories</Breadcrumb.Item>\n <Breadcrumb.Item link=\"javascript:void(0);\">Women’s Clothing</Breadcrumb.Item>\n <Breadcrumb.Item link=\"javascript:void(0);\">Blouses & Shirts</Breadcrumb.Item>\n <Breadcrumb.Item>T-shirts</Breadcrumb.Item>\n </Breadcrumb>,\n mountNode);
It is used to inform the user of the current position and the position of the current page in the entire site. It is an auxiliary navigation method and is applicable to a clear and multi-level structure of the website. Each layer of content is a hierarchical ownership relationship, which is convenient for users to return. One or all levels of pages.
\nParam | \nDescription | \nType | \nDefault Value | \n
---|---|---|---|
children | \nChildren components, hsould be an Breadcrumb.Item | \ncustom | \n- | \n
maxNode | \nThe maximum number of breadcrumbs is displayed and the excess is hidden, can set auto compute maximum number | \nNumber | \n100, 'auto' | \n
separator | \nSeparator, can be text or Icon | \nReactNode | \n<Icon type="arrow-right" /> | \n
component | \nSet Element type | \nString/Function | \n'nav' | \n
Param | \nDescription | \nType | \nDefault Value | \n
---|---|---|---|
link | \nThe breadcrumb item link, if this property is set, the node is <a /> , otherwise it is <span /> | \nString | \n- | \n
KeyBoard | \nDescripiton | \n
---|---|
Tab | \nswitch to next item | \n
用来告知用户当前的位置,以及当前页面在整个网站中的位置,属于一种辅助的导航方式,适用于清晰且具多层次结构的网站,每一层内容为层级归属关系,方便用户返回上一级或各个层级的页面。
\n参数 | \n说明 | \n类型 | \n默认值 | \n
---|---|---|---|
children | \n面包屑子节点,需传入 Breadcrumb.Item | \ncustom | \n- | \n
maxNode | \n面包屑最多显示个数,超出部分会被隐藏, 设置为 auto 会自动根据父元素的宽度适配。 | \nNumber/Enum | \n100 | \n
separator | \n分隔符,可以是文本或 Icon | \nReactNode | \n<Icon type="arrow-right" /> | \n
component | \n设置标签类型 | \nString/Function | \n'nav' | \n
参数 | \n说明 | \n类型 | \n默认值 | \n
---|---|---|---|
link | \n面包屑节点链接,如果设置这个属性,则该节点为<a /> ,否则是<span /> | \nString | \n- | \n
按键 | \n说明 | \n
---|---|
Tab | \n切换到下一项 | \n
When using icon Button component , we should add aria-label
to describe it. Please refer to ARIA and KeyBoard
for keyboard operation information.
import { Button, Icon } from '@alifd/next';\n\nReactDOM.render(<div>\n <Button.Group>\n <Button type=\"primary\" aria-label=\"prompt button\"><Icon type=\"prompt\" /></Button>\n <Button type=\"primary\" aria-label=\"clock button\"><Icon type=\"clock\" /></Button>\n <Button type=\"primary\" aria-label=\"set button\"><Icon type=\"set\" /></Button>\n </Button.Group>\n</div>, mountNode);
在使用不包含文本的icon Button组件时,我们需要添加aria-label
对其进行描述,键盘操作请参考ARIA and KeyBoard
。
import { Button, Icon } from '@alifd/next';\n\nReactDOM.render(<div>\n <Button.Group>\n <Button type=\"primary\" aria-label=\"prompt button\"><Icon type=\"prompt\" /></Button>\n <Button type=\"primary\" aria-label=\"clock button\"><Icon type=\"clock\" /></Button>\n <Button type=\"primary\" aria-label=\"set button\"><Icon type=\"set\" /></Button>\n </Button.Group>\n</div>, mountNode);
The types of button includes: primary, secondary, normal. Each one used to describe the importance level of a button.
\n","order":"0"},"codes":{"jsx":"import { Button } from '@alifd/next';\n\nReactDOM.render(import { Button } from '@alifd/next';\n\nReactDOM.render(<div>\n <Button type=\"normal\">Normal</Button> \n <Button type=\"primary\">Prirmary</Button> \n <Button type=\"secondary\">Secondary</Button>\n <br /><br />\n <Button type=\"normal\" text>Normal</Button> \n <Button type=\"primary\" text>Primary</Button> \n <Button type=\"secondary\" text>Secondary</Button>\n <br /><br />\n <Button type=\"normal\" warning>Normal</Button> \n <Button type=\"primary\" warning>Primary</Button> \n</div>, mountNode);
按钮有三种视觉层次:主按钮、次按钮、普通按钮。不同的类型可以用来区别按钮的重要程度。
\n","order":"0"},"codes":{"jsx":"import { Button } from '@alifd/next';\n\nReactDOM.render(import { Button } from '@alifd/next';\n\nReactDOM.render(<div>\n <Button type=\"normal\">Normal</Button> \n <Button type=\"primary\">Prirmary</Button> \n <Button type=\"secondary\">Secondary</Button>\n <br /><br />\n <Button type=\"normal\" text>Normal</Button> \n <Button type=\"primary\" text>Primary</Button> \n <Button type=\"secondary\" text>Secondary</Button>\n <br /><br />\n <Button type=\"normal\" warning>Normal</Button> \n <Button type=\"primary\" warning>Primary</Button> \n</div>, mountNode);
By default, a Button component is rendered by a html <button>
tag, its render behavior could be modified by a props named component
, which should be set to button
or a
.
import { Button } from '@alifd/next';\n\nconst props = {\n component: 'a',\n href: 'http://www.alibaba.com',\n target: '_blank'\n};\n\nReactDOM.render(<div>\n <Button {...props} type=\"primary\">alibaba.com</Button> \n <Button {...props} type=\"secondary\">alibaba.com</Button> \n <Button {...props} type=\"normal\">alibaba.com</Button>\n</div>, mountNode);
默认情况下 Button 组件使用 <button>
标签来渲染按钮,通过 component
属性可以自定义 Button 的标签类型。\n可选值为 button
和 a
。
import { Button } from '@alifd/next';\n\nconst props = {\n component: 'a',\n href: 'http://www.alibaba.com',\n target: '_blank'\n};\n\nReactDOM.render(<div>\n <Button {...props} type=\"primary\">alibaba.com</Button> \n <Button {...props} type=\"secondary\">alibaba.com</Button> \n <Button {...props} type=\"normal\">alibaba.com</Button>\n</div>, mountNode);
Disable a Button by adding disabled
attribute.
import { Button } from '@alifd/next';\n\nReactDOM.render(<div>\n <Button type=\"primary\">Primary</Button> \n <Button component=\"a\" type=\"primary\" disabled>Primary</Button>\n <br />\n <br />\n <Button type=\"secondary\">Secondary</Button> \n <Button type=\"secondary\" disabled>Secondary</Button>\n <br />\n <br />\n <Button type=\"normal\">Normal</Button> \n <Button type=\"normal\" disabled>Normal</Button>\n <br />\n <br />\n <div>\n <div className=\"ghost-light-background\">\n <Button ghost=\"light\" disabled>Ghost Light</Button>\n </div>\n <div className=\"ghost-dark-background\">\n <Button ghost=\"dark\" disabled>Ghost Dark</Button>\n </div>\n </div>\n</div>, mountNode);
.ghost-light-background {\n display: inline-block;\n height: 100px;\n line-height: 100px;\n width: 50%;\n background: #EBECF0;\n margin-bottom: 20px;\n padding-left:10px;\n box-sizing: border-box;\n}\n.ghost-dark-background {\n display: inline-block;\n height: 100px;\n line-height: 100px;\n width: 50%;\n background: #333;\n margin-bottom: 20px;\n padding-left:10px;\n box-sizing: border-box;\n}
添加 disabled
属性即可让按钮处于不可用状态,同时按钮样式也会改变。
import { Button } from '@alifd/next';\n\nReactDOM.render(<div>\n <Button type=\"primary\">Primary</Button> \n <Button component=\"a\" type=\"primary\" disabled>Primary</Button>\n <br />\n <br />\n <Button type=\"secondary\">Secondary</Button> \n <Button type=\"secondary\" disabled>Secondary</Button>\n <br />\n <br />\n <Button type=\"normal\">Normal</Button> \n <Button type=\"normal\" disabled>Normal</Button>\n <br />\n <br />\n <div>\n <div className=\"ghost-light-background\">\n <Button ghost=\"light\" disabled>Ghost Light</Button>\n </div>\n <div className=\"ghost-dark-background\">\n <Button ghost=\"dark\" disabled>Ghost Dark</Button>\n </div>\n </div>\n</div>, mountNode);
.ghost-light-background {\n display: inline-block;\n height: 100px;\n line-height: 100px;\n width: 50%;\n background: #EBECF0;\n margin-bottom: 20px;\n padding-left:10px;\n box-sizing: border-box;\n}\n.ghost-dark-background {\n display: inline-block;\n height: 100px;\n line-height: 100px;\n width: 50%;\n background: #333;\n margin-bottom: 20px;\n padding-left:10px;\n box-sizing: border-box;\n}
Ghost button is usually used for colored backgrounds. Change a Button to ghost by adding ghost
attribute,\nand set the attribute's value to light
or darked
based on the color depth.
import { Button } from '@alifd/next';\n\nReactDOM.render(<div style={{ clear: 'both' }}>\n <div className=\"ghost-light-background\">\n <Button ghost=\"light\">Ghost light</Button>\n </div>\n <div className=\"ghost-dark-background\">\n <Button ghost=\"dark\">Ghost dark</Button>\n </div>\n</div>, mountNode);
.ghost-light-background {\n display: inline-block;\n height: 100px;\n line-height: 100px;\n width: 50%;\n background: #EBECF0;\n margin-bottom: 20px;\n padding-left:10px;\n box-sizing: border-box;\n}\n.ghost-dark-background {\n display: inline-block;\n height: 100px;\n line-height: 100px;\n width: 50%;\n background: #333;\n margin-bottom: 20px;\n padding-left:10px;\n box-sizing: border-box;\n}
幽灵按钮通常用在有色背景下,可以使用 ghost
属性开启,此时 Button 为透明背景。对于浅色背景和深色背景,通过取值 light
, dark
可以配置使用幽灵按钮的场景。
import { Button } from '@alifd/next';\n\nReactDOM.render(<div style={{ clear: 'both' }}>\n <div className=\"ghost-light-background\">\n <Button ghost=\"light\">Ghost light</Button>\n </div>\n <div className=\"ghost-dark-background\">\n <Button ghost=\"dark\">Ghost dark</Button>\n </div>\n</div>, mountNode);
.ghost-light-background {\n display: inline-block;\n height: 100px;\n line-height: 100px;\n width: 50%;\n background: #EBECF0;\n margin-bottom: 20px;\n padding-left:10px;\n box-sizing: border-box;\n}\n.ghost-dark-background {\n display: inline-block;\n height: 100px;\n line-height: 100px;\n width: 50%;\n background: #333;\n margin-bottom: 20px;\n padding-left:10px;\n box-sizing: border-box;\n}
Button.Group
could be used to combine multiple Buttons.
import { Button, Icon } from '@alifd/next';\n\nReactDOM.render(<div>\n <Button.Group>\n <Button type=\"primary\">OK</Button>\n <Button type=\"secondary\">Cancel</Button>\n </Button.Group>\n \n <Button.Group>\n <Button disabled>Left</Button>\n <Button disabled>Middle</Button>\n <Button disabled>Right</Button>\n </Button.Group>\n <br />\n <br />\n\n <Button.Group>\n <Button type=\"primary\"><Icon type=\"arrow-left\" /> Backward</Button>\n <Button type=\"primary\">Forward <Icon type=\"arrow-right\" /></Button>\n </Button.Group>\n \n <Button.Group>\n <Button type=\"primary\"><Icon type=\"prompt\" /></Button>\n <Button type=\"primary\"><Icon type=\"clock\" /></Button>\n <Button type=\"primary\"><Icon type=\"set\" /></Button>\n </Button.Group>\n</div>, mountNode);
Button.Group
子组件用于将多个按钮组合在一个容器中。
import { Button, Icon } from '@alifd/next';\n\nReactDOM.render(<div>\n <Button.Group>\n <Button type=\"primary\">OK</Button>\n <Button type=\"secondary\">Cancel</Button>\n </Button.Group>\n \n <Button.Group>\n <Button disabled>Left</Button>\n <Button disabled>Middle</Button>\n <Button disabled>Right</Button>\n </Button.Group>\n <br />\n <br />\n\n <Button.Group>\n <Button type=\"primary\"><Icon type=\"arrow-left\" /> Backward</Button>\n <Button type=\"primary\">Forward <Icon type=\"arrow-right\" /></Button>\n </Button.Group>\n \n <Button.Group>\n <Button type=\"primary\"><Icon type=\"prompt\" /></Button>\n <Button type=\"primary\"><Icon type=\"clock\" /></Button>\n <Button type=\"primary\"><Icon type=\"set\" /></Button>\n </Button.Group>\n</div>, mountNode);
Button could contain Icon as its children, the default size of Icon is controlled by the Button size. And it can be manually controlled by using iconSize
prop.
import { Button, Icon } from '@alifd/next';\n\nReactDOM.render(<div>\n <Button><Icon type=\"atm\" /> ATM</Button> \n <Button text><Icon type=\"atm\" /> ATM</Button> \n <Button warning><Icon type=\"atm\" /> ATM</Button> \n <Button iconSize=\"xxs\"><Icon type=\"arrow-left\" /> ARROW</Button> \n</div>, mountNode);
Button 可以嵌入 Icon,默认情况下 Icon 尺寸自动跟随 Button 的尺寸。如果用户想要控制 Icon 的大小,可以通过 iconSize
属性进行设置。
import { Button, Icon } from '@alifd/next';\n\nReactDOM.render(<div>\n <Button><Icon type=\"atm\" /> ATM</Button> \n <Button text><Icon type=\"atm\" /> ATM</Button> \n <Button warning><Icon type=\"atm\" /> ATM</Button> \n <Button iconSize=\"xxs\"><Icon type=\"arrow-left\" /> ARROW</Button> \n</div>, mountNode);
Button has a inner state loading
to control if a Button is in loading. It could be changed by setting loading
attribute.
import { Button } from '@alifd/next';\n\nclass Demo extends React.Component {\n constructor(props, context) {\n super(props, context);\n\n this.state = {\n loading: false\n };\n }\n\n setLoading = () => {\n this.setState({ loading: true });\n }\n\n render() {\n return (<div>\n <Button type=\"secondary\" loading>Loading</Button> \n <Button type=\"primary\" loading={this.state.loading} onClick={this.setLoading}>Click to loading</Button>\n </div>);\n }\n}\n\nReactDOM.render(<Demo/>, mountNode);
通过设置 loading
属性即可以让按钮处于加载状态。
import { Button } from '@alifd/next';\n\nclass Demo extends React.Component {\n constructor(props, context) {\n super(props, context);\n\n this.state = {\n loading: false\n };\n }\n\n setLoading = () => {\n this.setState({ loading: true });\n }\n\n render() {\n return (<div>\n <Button type=\"secondary\" loading>Loading</Button> \n <Button type=\"primary\" loading={this.state.loading} onClick={this.setLoading}>Click to loading</Button>\n </div>);\n }\n}\n\nReactDOM.render(<Demo/>, mountNode);
The size of a Button is controlled by a size
attribute, supporting large
, medium
, small
, the default value is medium
.
import { Button, Icon } from '@alifd/next';\n\nReactDOM.render(<div>\n <Button type=\"primary\" size=\"large\"><Icon type=\"atm\" />Large</Button> \n <Button type=\"primary\"><Icon type=\"atm\" />Medium</Button> \n <Button type=\"primary\" size=\"small\"><Icon type=\"atm\" />Small</Button>\n <br />\n <br />\n <Button.Group size=\"large\">\n <Button>Button</Button>\n <Button>Button</Button>\n <Button>Button</Button>\n </Button.Group>\n</div>, mountNode);
可以通过设置 size
属性控制按钮的尺寸,可选值为 large
medium
small
,其中默认值为 medium
。
import { Button, Icon } from '@alifd/next';\n\nReactDOM.render(<div>\n <Button type=\"primary\" size=\"large\"><Icon type=\"atm\" />Large</Button> \n <Button type=\"primary\"><Icon type=\"atm\" />Medium</Button> \n <Button type=\"primary\" size=\"small\"><Icon type=\"atm\" />Small</Button>\n <br />\n <br />\n <Button.Group size=\"large\">\n <Button>Button</Button>\n <Button>Button</Button>\n <Button>Button</Button>\n </Button.Group>\n</div>, mountNode);
Button used to trigger an action.
\nButtons are used for emphasizing important functions on your page.
\nParam | \nDescription | \nType | \nDefault Value | \n
---|---|---|---|
size | \nSize of button return: 'small', 'medium', 'large' | \nEnum | \n'medium' | \n
type | \nTypeo of button return: 'primary', 'secondary', 'normal' | \nEnum | \n'normal' | \n
iconSize | \nSize of icon in button return: 'xxs', 'xs', 'small', 'medium', 'large', 'xl', 'xxl', 'xxxl' | \nEnum | \n- | \n
htmlType | \nOriginal html type return: 'submit', 'reset', 'button' | \nEnum | \n'button' | \n
component | \nThe html tag to be rendered return: 'button', 'a', 'div', 'span' | \nEnum | \n'button' | \n
loading | \nLoading state of a button | \nBoolean | \nfalse | \n
ghost | \nSetting ghost button return: true, false, 'light', 'dark' | \nEnum | \nfalse | \n
text | \nSetting text button | \nBoolean | \nfalse | \n
warning | \nSettting warning button | \nBoolean | \nfalse | \n
disabled | \nwhether is disabled | \nBoolean | \nfalse | \n
onClick | \nCallback of click event signature: Function(e: Object) => void return: _e_: {Object} Event Object | \nFunction | \n() => {} | \n
Param | \nDescription | \nType | \nDefault Value | \n
---|---|---|---|
size | \nSize of buttons in group | \nString | \n'medium' | \n
KeyBoard | \nDescripiton | \n
---|---|
Enter | \nTrigger the onClick event | \n
SPACE | \nTrigger the onClick event | \n
按钮用于开始一个即时操作。
\n标记了一个(或封装一组)操作命令,响应用户点击行为,触发相应的业务逻辑。
\n参数 | \n说明 | \n类型 | \n默认值 | \n
---|---|---|---|
size | \n按钮的尺寸 可选值: 'small', 'medium', 'large' | \nEnum | \n'medium' | \n
type | \n按钮的类型 可选值: 'primary', 'secondary', 'normal' | \nEnum | \n'normal' | \n
iconSize | \n按钮中 Icon 的尺寸,用于替代 Icon 的默认大小 可选值: 'xxs', 'xs', 'small', 'medium', 'large', 'xl', 'xxl', 'xxxl' | \nEnum | \n- | \n
htmlType | \n当 component = 'button' 时,设置 button 标签的 type 值 可选值: 'submit', 'reset', 'button' | \nEnum | \n'button' | \n
component | \n设置标签类型 可选值: 'button', 'a', 'div', 'span' | \nEnum | \n'button' | \n
loading | \n设置按钮的载入状态 | \nBoolean | \nfalse | \n
ghost | \n是否为幽灵按钮 可选值: true, false, 'light', 'dark' | \nEnum | \nfalse | \n
text | \n是否为文本按钮 | \nBoolean | \nfalse | \n
warning | \n是否为警告按钮 | \nBoolean | \nfalse | \n
disabled | \n是否禁用 | \nBoolean | \nfalse | \n
onClick | \n点击按钮的回调 签名: Function(e: Object) => void 参数: _e_: {Object} Event Object | \nFunction | \n() => {} | \n
参数 | \n说明 | \n类型 | \n默认值 | \n
---|---|---|---|
size | \n统一设置 Button 组件的按钮大小 | \nString | \n'medium' | \n
按键 | \n说明 | \n
---|---|
Enter | \n触发onClick事件 | \n
SPACE | \n触发onClick事件 | \n
A basic fullscreen calendar.
\n","order":"0"},"codes":{"jsx":"import { Calendar } from '@alifd/next';\nimport moment from 'moment';\n\nfunction onDateChange(value) {\n console.log(value.format('L'));\n}\n\nReactDOM.render(import { Calendar } from '@alifd/next';\nimport moment from 'moment';\n\nfunction onDateChange(value) {\n console.log(value.format('L'));\n}\n\nReactDOM.render(<div>\n <Calendar onSelect={onDateChange} defaultValue={moment().add(1, 'days')} /></div>, mountNode);
最简单的日历用法,用户可以切换年/月。
\n","order":"0"},"codes":{"jsx":"import { Calendar } from '@alifd/next';\nimport moment from 'moment';\n\nfunction onDateChange(value) {\n console.log(value.format('L'));\n}\n\nReactDOM.render(import { Calendar } from '@alifd/next';\nimport moment from 'moment';\n\nfunction onDateChange(value) {\n console.log(value.format('L'));\n}\n\nReactDOM.render(<div>\n <Calendar onSelect={onDateChange} defaultValue={moment().add(1, 'days')} /></div>, mountNode);
A card calendar is usually used for embedding in a container with limiting width and height.
\n","order":"1"},"codes":{"jsx":"import { Calendar } from '@alifd/next';\n\nfunction onDateChange(value) {\n console.log(value);\n}\n\nReactDOM.render(import { Calendar } from '@alifd/next';\n\nfunction onDateChange(value) {\n console.log(value);\n}\n\nReactDOM.render(<div className=\"wrapped-calendar\">\n <Calendar onSelect={onDateChange} shape=\"card\" />\n</div>, mountNode);
.wrapped-calendar {\n width: 300px;\n border: 1px solid #C4C6CF;\n border-radius: 3px;\n padding: 8px;\n}
可以将 card
形态的日历组件嵌套在宽高受限的容器中。
import { Calendar } from '@alifd/next';\n\nfunction onDateChange(value) {\n console.log(value);\n}\n\nReactDOM.render(<div className=\"wrapped-calendar\">\n <Calendar onSelect={onDateChange} shape=\"card\" />\n</div>, mountNode);
.wrapped-calendar {\n width: 300px;\n border: 1px solid #C4C6CF;\n border-radius: 3px;\n padding: 8px;\n}
Render custom contents in dateCellRender
and monthCellRender
.
import { Calendar } from '@alifd/next';\nimport moment from 'moment';\n\nconst currentDate = moment();\nconst localeData = currentDate.clone().localeData();\nconst monthLocale = localeData.monthsShort();\n\n\nfunction dateCellRender(date) {\n const dateNum = date.date();\n if (currentDate.month() !== date.month()) {\n return dateNum;\n }\n\n let eventList;\n switch (dateNum) {\n case 1:\n eventList = [\n { type: 'primary', content: 'Event 1' },\n { type: 'normal', content: 'Event 2' }\n ];\n break;\n case 10:\n eventList = [\n { type: 'normal', content: 'Event 3' },\n { type: 'normal', content: 'Event 4' }\n ];\n break;\n case 11:\n eventList = [\n { type: 'primary', content: 'Event 5' },\n { type: 'primary', content: 'Event 6' }\n ];\n break;\n default:\n eventList = [];\n }\n\n return (<div className=\"custom-calendar-cell\">\n <div className=\"custom-calendar-cell-value\">{dateNum}</div>\n <div className=\"custom-calendar-cell-content\">\n <ul className=\"event-list\">\n {eventList.map((item, key) => <li className={`${item.type}-event`} key={key}>{item.content}</li>)}\n </ul>\n </div>\n </div>);\n}\n\nfunction monthCellRender(date) {\n if (currentDate.month() === date.month()) {\n return (<div>\n <div>{monthLocale[date.month()]}</div>\n <div>Events</div>\n </div>);\n }\n return monthLocale[date.month()];\n}\n\nReactDOM.render(<Calendar dateCellRender={dateCellRender} monthCellRender={monthCellRender} />, mountNode);
.custom-calendar-guide {\n width: 270px;\n border: 1px solid #C4C6CF;\n border-radius: 3px;\n overflow: hidden;\n margin-top: 20px;\n}\n\n.custom-calendar-cell-content {\n height: 50px;\n text-align: left;\n}\n\n.event-list {\n margin: 0;\n padding: 0;\n list-style: none;\n}\n\n.primary-event {\n color: white;\n background: red;\n border-radius: 3px;\n padding-left: 10px;\n margin-bottom: 3px;\n}\n\n.normal-event {\n color: white;\n background: blue;\n border-radius: 3px;\n padding-left: 10px;\n margin-bottom: 3px;\n}
通过 dateCellRender
和 monthCellRender
用户可以在日历中添加自定义内容。
import { Calendar } from '@alifd/next';\nimport moment from 'moment';\n\nconst currentDate = moment();\nconst localeData = currentDate.clone().localeData();\nconst monthLocale = localeData.monthsShort();\n\n\nfunction dateCellRender(date) {\n const dateNum = date.date();\n if (currentDate.month() !== date.month()) {\n return dateNum;\n }\n\n let eventList;\n switch (dateNum) {\n case 1:\n eventList = [\n { type: 'primary', content: 'Event 1' },\n { type: 'normal', content: 'Event 2' }\n ];\n break;\n case 10:\n eventList = [\n { type: 'normal', content: 'Event 3' },\n { type: 'normal', content: 'Event 4' }\n ];\n break;\n case 11:\n eventList = [\n { type: 'primary', content: 'Event 5' },\n { type: 'primary', content: 'Event 6' }\n ];\n break;\n default:\n eventList = [];\n }\n\n return (<div className=\"custom-calendar-cell\">\n <div className=\"custom-calendar-cell-value\">{dateNum}</div>\n <div className=\"custom-calendar-cell-content\">\n <ul className=\"event-list\">\n {eventList.map((item, key) => <li className={`${item.type}-event`} key={key}>{item.content}</li>)}\n </ul>\n </div>\n </div>);\n}\n\nfunction monthCellRender(date) {\n if (currentDate.month() === date.month()) {\n return (<div>\n <div>{monthLocale[date.month()]}</div>\n <div>Events</div>\n </div>);\n }\n return monthLocale[date.month()];\n}\n\nReactDOM.render(<Calendar dateCellRender={dateCellRender} monthCellRender={monthCellRender} />, mountNode);
.custom-calendar-guide {\n width: 270px;\n border: 1px solid #C4C6CF;\n border-radius: 3px;\n overflow: hidden;\n margin-top: 20px;\n}\n\n.custom-calendar-cell-content {\n height: 50px;\n text-align: left;\n}\n\n.event-list {\n margin: 0;\n padding: 0;\n list-style: none;\n}\n\n.primary-event {\n color: white;\n background: red;\n border-radius: 3px;\n padding-left: 10px;\n margin-bottom: 3px;\n}\n\n.normal-event {\n color: white;\n background: blue;\n border-radius: 3px;\n padding-left: 10px;\n margin-bottom: 3px;\n}
Change default visible month by defaultVisibleMonth
.
import { Calendar } from '@alifd/next';\nimport moment from 'moment';\n\nfunction onSelect(value) {\n console.log(value.format('L'));\n}\n\nfunction onVisibleMonthChange(value, reason) {\n console.log('Visible month changed to %s from <%s>', value.format('YYYY-MM'), reason);\n}\n\nReactDOM.render(<Calendar onSelect={onSelect} defaultVisibleMonth={() => moment('2018-01', 'YYYY-MM', true)} onVisibleMonthChange={onVisibleMonthChange} />, mountNode);
日历组件默认使用当前月作为展示的月份,用户可以可以通过 defaultVisibleMonth
属性进行定制。并可以通过 onVisibleMonthChange
属性监听面板可视月份的变化。
import { Calendar } from '@alifd/next';\nimport moment from 'moment';\n\nfunction onSelect(value) {\n console.log(value.format('L'));\n}\n\nfunction onVisibleMonthChange(value, reason) {\n console.log('Visible month changed to %s from <%s>', value.format('YYYY-MM'), reason);\n}\n\nReactDOM.render(<Calendar onSelect={onSelect} defaultVisibleMonth={() => moment('2018-01', 'YYYY-MM', true)} onVisibleMonthChange={onVisibleMonthChange} />, mountNode);
Disable specific dates by disabledDate
.
import { Calendar } from '@alifd/next';\nimport moment from 'moment';\n\nconst currentDate = moment();\nconst disabledDate = function (date) {\n return date.valueOf() > currentDate.valueOf();\n};\n\nReactDOM.render(<div className=\"wrapped-calendar\">\n <Calendar disabledDate={disabledDate} shape=\"card\" />\n</div>, mountNode);
.wrapped-calendar {\n width: 300px;\n border: 1px solid #C4C6CF;\n border-radius: 3px;\n padding: 8px;\n}
可以通过 disabledDate
属性禁止用户选择某些日期。
import { Calendar } from '@alifd/next';\nimport moment from 'moment';\n\nconst currentDate = moment();\nconst disabledDate = function (date) {\n return date.valueOf() > currentDate.valueOf();\n};\n\nReactDOM.render(<div className=\"wrapped-calendar\">\n <Calendar disabledDate={disabledDate} shape=\"card\" />\n</div>, mountNode);
.wrapped-calendar {\n width: 300px;\n border: 1px solid #C4C6CF;\n border-radius: 3px;\n padding: 8px;\n}
Locale of date values come from moment
, setting to dispaly Chinese with moment.locale('zh-cn')
.
import { Calendar } from '@alifd/next';\nimport moment from 'moment';\n\n// Setting moment locale to Chinese\nmoment.locale('zh-cn');\n\nReactDOM.render(<Calendar />, mountNode);
日期时间的多语言来源于 moment ,可以通过 moment.locale('zh-cn')
来设置显示中文。
import { Calendar } from '@alifd/next';\nimport moment from 'moment';\n\n// Setting moment locale to Chinese\nmoment.locale('zh-cn');\n\nReactDOM.render(<Calendar />, mountNode);
A Lunar calendar.
\n","order":"0"},"codes":{"jsx":"import { Calendar } from '@alifd/next';\nimport moment from 'moment';\nimport solarLunar from 'solarlunar';\n\nfunction onDateChange(value) {\n console.log(value.format('L'));\n}\n\nfunction dateCellRender(value) {\n const solar2lunarData = solarLunar.solar2lunar(value.year(), value.month(), value.date());\n\n return (import { Calendar } from '@alifd/next';\nimport moment from 'moment';\nimport solarLunar from 'solarlunar';\n\nfunction onDateChange(value) {\n console.log(value.format('L'));\n}\n\nfunction dateCellRender(value) {\n const solar2lunarData = solarLunar.solar2lunar(value.year(), value.month(), value.date());\n\n return (<div className=\"custom-cell\">\n {value.date()}\n <span>{solar2lunarData.lDay === 1 ? solar2lunarData.monthCn: solar2lunarData.dayCn}</span>\n </div>);\n}\n\n\nReactDOM.render(<div>\n <Calendar onSelect={onDateChange} dateCellRender={dateCellRender} defaultValue={moment().add(1, 'days')} /></div>, mountNode);
.custom-cell {\n width: 100%;\n height: 70px;\n display: flex;\n flex-direction: column;\n justify-content: space-between;\n align-items: flex-end;\n}
农历
\n","order":"0"},"codes":{"jsx":"import { Calendar } from '@alifd/next';\nimport moment from 'moment';\nimport solarLunar from 'solarlunar';\n\nfunction onDateChange(value) {\n console.log(value.format('L'));\n}\n\nfunction dateCellRender(value) {\n const solar2lunarData = solarLunar.solar2lunar(value.year(), value.month(), value.date());\n\n return (import { Calendar } from '@alifd/next';\nimport moment from 'moment';\nimport solarLunar from 'solarlunar';\n\nfunction onDateChange(value) {\n console.log(value.format('L'));\n}\n\nfunction dateCellRender(value) {\n const solar2lunarData = solarLunar.solar2lunar(value.year(), value.month(), value.date());\n\n return (<div className=\"custom-cell\">\n {value.date()}\n <span>{solar2lunarData.lDay === 1 ? solar2lunarData.monthCn: solar2lunarData.dayCn}</span>\n </div>);\n}\n\n\nReactDOM.render(<div>\n <Calendar onSelect={onDateChange} dateCellRender={dateCellRender} defaultValue={moment().add(1, 'days')} /></div>, mountNode);
.custom-cell {\n width: 100%;\n height: 70px;\n display: flex;\n flex-direction: column;\n justify-content: space-between;\n align-items: flex-end;\n}
A calendar panel is usually used for embedding in a popup container.
\n","order":"5"},"codes":{"jsx":"import { Calendar } from '@alifd/next';\nimport moment from 'moment';\n\nReactDOM.render(import { Calendar } from '@alifd/next';\nimport moment from 'moment';\n\nReactDOM.render(<div>\n <Calendar shape=\"panel\" value={moment().add(1, 'days')} />\n</div>, mountNode);
日历面板通用用于嵌套在弹层容器中。
\n","order":"5"},"codes":{"jsx":"import { Calendar } from '@alifd/next';\nimport moment from 'moment';\n\nReactDOM.render(import { Calendar } from '@alifd/next';\nimport moment from 'moment';\n\nReactDOM.render(<div>\n <Calendar shape=\"panel\" value={moment().add(1, 'days')} />\n</div>, mountNode);
A container for displaying calendar data.
\nCalendar could be used to display dates, such as schedules, timetables, price calendar, lunar calendar, and so on.
\nCalendar use moment as a core part to manipulate and display time values. For real usage, it could be used with the latest moment
package. Setting moment's locale by:
import moment from 'moment';\n\nmoment.locale('zh-cn');
Param | \nDescription | \nType | \nDefault Value | \n
---|---|---|---|
defaultValue | \nDefault value of calendar | \ncustom | \n- | \n
shape | \nShape of calendar option: 'card', 'fullscreen', 'panel' | \nEnum | \n'fullscreen' | \n
value | \nValue of calendar | \ncustom | \n- | \n
mode | \nMode of panel option: 'date', 'month', 'year' | \nEnum | \n'date' | \n
showOtherMonth | \nShow dates of other month in current date | \nBoolean | \ntrue | \n
defaultVisibleMonth | \nDefault visible month of panel signature: Function() => void | \nFunction | \n- | \n
onSelect | \nCallback when select a date signature: Function(value: Object) => void parameter: value: {Object} date object | \nFunction | \nfunc.noop | \n
onModeChange | \nCallback when change mode 签名: Function(mode: string) => void 参数: mode: {string} mode type: date month year | \nFunction | \nfunc.noop | \n
dateCellRender | \nRender function for date cell signature: Function(value: Object) => ReactNode parameter: value: {Object} date object return: {ReactNode} null | \nFunction | \n(value) => value.date() | \n
monthCellRender | \nRender function for month cell signature: Function(calendarDate: Object) => ReactNode parameter: calendarDate: {Object} current date object return: {ReactNode} null | \nFunction | \n- | \n
yearRange | \nYear Range,[START_YEAR, END_YEAR] (only shape in ‘card’, 'fullscreen') | \nArray<Number> | \n- | \n
disabledDate | \nFunction to disable dates signature: Function(calendarDate: Object) => Boolean parameter: calendarDate: {Object} current date object view: {Enum} current view type: 'year', 'month', 'date' return: {Boolean} null | \nFunction | \n- | \n
按照日历形式展示数据的容器。
\n日历组件是一个偏向于展示与受控的基础组件,可用于日程、课表、价格日历、农历展示等。
\n由于 Calendar 组件内部使用 moment 对象来设置日期(请使用最新版 moment),部分 Locale 读取自 moment,因此用户需要在外部使用时正确的设置 moment 的 locale 。
\nimport moment from 'moment';\n\nmoment.locale('zh-cn');
参数 | \n说明 | \n类型 | \n默认值 | \n
---|---|---|---|
defaultValue | \n默认选中的日期(moment 对象) | \ncustom | \n- | \n
shape | \n展现形态 可选值: 'card', 'fullscreen', 'panel' | \nEnum | \n'fullscreen' | \n
value | \n选中的日期值 (moment 对象) | \ncustom | \n- | \n
mode | \n面板模式 | \nEnum | \n- | \n
showOtherMonth | \n是否展示非本月的日期 | \nBoolean | \ntrue | \n
defaultVisibleMonth | \n默认展示的月份 签名: Function() => void | \nFunction | \n- | \n
onSelect | \n选择日期单元格时的回调 签名: Function(value: Object) => void 参数: value: {Object} 对应的日期值 (moment 对象) | \nFunction | \nfunc.noop | \n
onModeChange | \n面板模式变化时的回调 签名: Function(mode: String) => void 参数: mode: {String} 对应面板模式 date month year | \nFunction | \nfunc.noop | \n
onVisibleMonthChange | \n展现的月份变化时的回调 签名: Function(value: Object, reason: String) => void 参数: value: {Object} 显示的月份 (moment 对象) reason: {String} 触发月份改变原因 | \nFunction | \nfunc.noop | \n
dateCellRender | \n自定义日期渲染函数 签名: Function(value: Object) => ReactNode 参数: value: {Object} 日期值(moment对象) 返回值: {ReactNode} null | \nFunction | \nvalue => value.date() | \n
monthCellRender | \n自定义月份渲染函数 签名: Function(calendarDate: Object) => ReactNode 参数: calendarDate: {Object} 对应 Calendar 返回的自定义日期对象 返回值: {ReactNode} null | \nFunction | \n- | \n
yearRange | \n年份范围,[START_YEAR, END_YEAR] (只在shape 为 ‘card’, 'fullscreen' 下生效) | \nArray<Number> | \n- | \n
disabledDate | \n不可选择的日期 签名: Function(calendarDate: Object, view: String) => Boolean 参数: calendarDate: {Object} 对应 Calendar 返回的自定义日期对象 view: {String} 当前视图类型,year: 年, month: 月, date: 日 返回值: {Boolean} null | \nFunction | \n- | \n
A simple card with title and sub-title.
\n","order":"0"},"codes":{"jsx":"import { Card } from '@alifd/next';\n\nconst commonProps = {\n style: { width: 300 },\n subTitle: 'SubTitle',\n extra: 'Link'\n};\n\nReactDOM.render(import { Card } from '@alifd/next';\n\nconst commonProps = {\n style: { width: 300 },\n subTitle: 'SubTitle',\n extra: 'Link'\n};\n\nReactDOM.render(<div>\n <Card {...commonProps} title=\"Simple Card\">\n <div className=\"card-placeholder\"></div>\n </Card>\n</div>, mountNode);
.card-placeholder {\n height: 500px;\n text-align: center;\n background: #F7F8FA;\n}
最简单的用法。
\n","order":"0"},"codes":{"jsx":"import { Card } from '@alifd/next';\n\nconst commonProps = {\n style: { width: 300 },\n subTitle: 'SubTitle',\n extra: 'Link'\n};\n\nReactDOM.render(import { Card } from '@alifd/next';\n\nconst commonProps = {\n style: { width: 300 },\n subTitle: 'SubTitle',\n extra: 'Link'\n};\n\nReactDOM.render(<div>\n <Card {...commonProps} title=\"Simple Card\">\n <div className=\"card-placeholder\"></div>\n </Card>\n</div>, mountNode);
.card-placeholder {\n height: 500px;\n text-align: center;\n background: #F7F8FA;\n}
Customize default styles of a card.
\n","order":"2"},"codes":{"jsx":"import { Card } from '@alifd/next';\n\nReactDOM.render(Thank you, papa
\nThank you, papa
\nimport { Card } from '@alifd/next';\n\nReactDOM.render(<Card className=\"image-card\" contentHeight=\"auto\">\n <img src=\"https://img.alicdn.com/tfs/TB1FNIOSFXXXXaWXXXXXXXXXXXX-260-188.png\" alt=\"father day\" />\n <div className=\"custom-card\">\n <h3>Father's Day</h3>\n <p>Thank you, papa</p>\n </div>\n</Card>, mountNode);
.image-card {\n display: inline-block;\n text-align: center;\n}\n\n.custom-card p {\n color: #999;\n}
如果默认的卡片样式不能满足您的需求,除了通过 Fusion 配置平台修改,还可以通过传入自定义样式修改。\n如果 title
属性不传入任何值,则默认会去除整个头部区域。
Thank you, papa
\nThank you, papa
\nimport { Card } from '@alifd/next';\n\nReactDOM.render(<Card className=\"image-card\" contentHeight=\"auto\">\n <img src=\"https://img.alicdn.com/tfs/TB1FNIOSFXXXXaWXXXXXXXXXXXX-260-188.png\" alt=\"father day\" />\n <div className=\"custom-card\">\n <h3>Father's Day</h3>\n <p>Thank you, papa</p>\n </div>\n</Card>, mountNode);
.image-card {\n display: inline-block;\n text-align: center;\n}\n\n.custom-card p {\n color: #999;\n}
Setting contet height by contentHeight
, setting value to auto
will disabled the collapse behavior.
Card content
\nCard content
\nCard content
\nCard content
\nCard content
\nCard content
\nCard content
\nCard content
\nCard content
\nCard content
\nCard content
\nCard content
\nCard content
\nCard content
\nCard content
\nCard content
\nCard content
\nCard content
\nCard content
\nCard content
\nimport { Card } from '@alifd/next';\n\nconst commonProps = {\n style: { width: 300 },\n title: 'Title',\n subTitle: 'Sub-title'\n};\n\nReactDOM.render(<div>\n <Card {...commonProps} contentHeight=\"auto\">\n <div className=\"custom-content\">\n <p>Card content</p>\n <p>Card content</p>\n <p>Card content</p>\n <p>Card content</p>\n <p>Card content</p>\n </div>\n </Card>\n \n <Card {...commonProps} contentHeight={200}>\n <div className=\"custom-content\">\n <p>Card content</p>\n <p>Card content</p>\n <p>Card content</p>\n <p>Card content</p>\n <p>Card content</p>\n </div>\n </Card>\n</div>, mountNode);
.custom-content p {\n margin: 0;\n}
可以通过 contentHeight
属性自定义内容区的高度。例如取值为 auto
的时候会默认关闭卡片的收缩效果。
Card content
\nCard content
\nCard content
\nCard content
\nCard content
\nCard content
\nCard content
\nCard content
\nCard content
\nCard content
\nCard content
\nCard content
\nCard content
\nCard content
\nCard content
\nCard content
\nCard content
\nCard content
\nCard content
\nCard content
\nimport { Card } from '@alifd/next';\n\nconst commonProps = {\n style: { width: 300 },\n title: 'Title',\n subTitle: 'Sub-title'\n};\n\nReactDOM.render(<div>\n <Card {...commonProps} contentHeight=\"auto\">\n <div className=\"custom-content\">\n <p>Card content</p>\n <p>Card content</p>\n <p>Card content</p>\n <p>Card content</p>\n <p>Card content</p>\n </div>\n </Card>\n \n <Card {...commonProps} contentHeight={200}>\n <div className=\"custom-content\">\n <p>Card content</p>\n <p>Card content</p>\n <p>Card content</p>\n <p>Card content</p>\n <p>Card content</p>\n </div>\n </Card>\n</div>, mountNode);
.custom-content p {\n margin: 0;\n}
Customize card head by hasTitleBullet
and extra
.
import { Card, Button } from '@alifd/next';\n\nconst commonProps = {\n style: { width: 300 },\n title: 'Title',\n extra: <Button text>More</Button>\n};\n\nReactDOM.render(<div>\n <Card {...commonProps} showTitleBullet={false}>\n Card Content\n </Card>\n</div>, mountNode);
可以通过配置 hasTitleBullet
属性配置卡片标题是否显示项目符号。此外,extra
允许用户传入自定义的 React 组件。
import { Card, Button } from '@alifd/next';\n\nconst commonProps = {\n style: { width: 300 },\n title: 'Title',\n extra: <Button text>More</Button>\n};\n\nReactDOM.render(<div>\n <Card {...commonProps} showTitleBullet={false}>\n Card Content\n </Card>\n</div>, mountNode);
Combination with subcomponents to customize card styles
\n","order":"5"},"codes":{"jsx":"import { Card, Button } from '@alifd/next';\n\nReactDOM.render(\nimport { Card, Button } from '@alifd/next';\n\nReactDOM.render(\n <div>\n <Card\n className=\"free-card custom\"\n free\n >\n <Card.Media image=\"https://img.alicdn.com/tfs/TB1FNIOSFXXXXaWXXXXXXXXXXXX-260-188.png\" />\n <div className=\"free-card-main\">\n <Card.Header title=\"Title\" subTitle=\"Sub Title\" extra={<Button type=\"primary\" text>Link</Button>} />\n <Card.Divider />\n <Card.Content>\n Lorem ipsum dolor sit amet, est viderer iuvaret perfecto et.\n </Card.Content>\n <Card.Actions>\n <Button type=\"primary\" key=\"action1\" text>Action 1</Button>\n <Button type=\"primary\" key=\"action2\" text>Action 2</Button>\n </Card.Actions>\n </div>\n </Card>\n <br/>\n <Card\n className=\"free-card\"\n free\n >\n <Card.Media style={{ height: 140 }} image=\"https://img.alicdn.com/tfs/TB1FNIOSFXXXXaWXXXXXXXXXXXX-260-188.png\" />\n <Card.BulletHeader title=\"Title\" subTitle=\"Sub Title\" extra={<Button type=\"primary\" text>Link</Button>} />\n <Card.CollaspeContent contentHeight=\"auto\">\n Lorem ipsum dolor sit amet, est viderer iuvaret perfecto et. Ne petentium quaerendum nec, eos ex recteque mediocritatem, ex usu assum legendos temporibus. Ius feugiat pertinacia an, cu verterem praesent quo.\n </Card.CollaspeContent>\n <Card.Actions>\n <Button type=\"primary\" key=\"action1\" text>Action 1</Button>\n <Button type=\"primary\" key=\"action2\" text>Action 2</Button>\n </Card.Actions>\n </Card>\n\n <Card\n className=\"free-card\"\n free\n >\n <Card.Media style={{ height: 140 }} image=\"https://img.alicdn.com/tfs/TB1FNIOSFXXXXaWXXXXXXXXXXXX-260-188.png\" />\n <Card.Header title=\"Title\" subTitle=\"Sub Title\" extra={<Button type=\"primary\" text>Link</Button>} />\n <Card.Divider />\n <Card.Content>\n Lorem ipsum dolor sit amet, est viderer iuvaret perfecto et. Ne petentium quaerendum nec, eos ex recteque mediocritatem, ex usu assum legendos temporibus. Ius feugiat pertinacia an, cu verterem praesent quo.\n </Card.Content>\n <Card.Actions>\n <Button type=\"primary\" key=\"action1\" text>Action 1</Button>\n <Button type=\"primary\" key=\"action2\" text>Action 2</Button>\n </Card.Actions>\n </Card>\n </div>\n , mountNode);
.free-card {\n display: inline-block;\n width: 300px;\n vertical-align: top;\n}\n.free-card + .free-card {\n margin-left: 20px;\n}\n\n.free-card.custom {\n display: flex;\n justify-content: space-between;\n width: 500px;\n height: 200px;\n}\n\n.free-card.custom .next-card-media {\n height: 100%;\n width: 200px;\n flex-shrink: 0;\n}\n\n.free-card-main {\n display: flex;\n flex-direction: column;\n align-items: stretch;\n}\n\n.free-card-main .next-card-content-container {\n flex: 1;\n}\n\n.free-card-main .next-card-actions {\n text-align: right;\n}
与子组件的组合来自定义卡片样式
\n","order":"5"},"codes":{"jsx":"import { Card, Button } from '@alifd/next';\n\nReactDOM.render(\nimport { Card, Button } from '@alifd/next';\n\nReactDOM.render(\n <div>\n <Card\n className=\"free-card custom\"\n free\n >\n <Card.Media image=\"https://img.alicdn.com/tfs/TB1FNIOSFXXXXaWXXXXXXXXXXXX-260-188.png\" />\n <div className=\"free-card-main\">\n <Card.Header title=\"Title\" subTitle=\"Sub Title\" extra={<Button type=\"primary\" text>Link</Button>} />\n <Card.Divider />\n <Card.Content>\n Lorem ipsum dolor sit amet, est viderer iuvaret perfecto et.\n </Card.Content>\n <Card.Actions>\n <Button type=\"primary\" key=\"action1\" text>Action 1</Button>\n <Button type=\"primary\" key=\"action2\" text>Action 2</Button>\n </Card.Actions>\n </div>\n </Card>\n <br/>\n <Card\n className=\"free-card\"\n free\n >\n <Card.Media style={{ height: 140 }} image=\"https://img.alicdn.com/tfs/TB1FNIOSFXXXXaWXXXXXXXXXXXX-260-188.png\" />\n <Card.BulletHeader title=\"Title\" subTitle=\"Sub Title\" extra={<Button type=\"primary\" text>Link</Button>} />\n <Card.CollaspeContent contentHeight=\"auto\">\n Lorem ipsum dolor sit amet, est viderer iuvaret perfecto et. Ne petentium quaerendum nec, eos ex recteque mediocritatem, ex usu assum legendos temporibus. Ius feugiat pertinacia an, cu verterem praesent quo.\n </Card.CollaspeContent>\n <Card.Actions>\n <Button type=\"primary\" key=\"action1\" text>Action 1</Button>\n <Button type=\"primary\" key=\"action2\" text>Action 2</Button>\n </Card.Actions>\n </Card>\n\n <Card\n className=\"free-card\"\n free\n >\n <Card.Media style={{ height: 140 }} image=\"https://img.alicdn.com/tfs/TB1FNIOSFXXXXaWXXXXXXXXXXXX-260-188.png\" />\n <Card.Header title=\"Title\" subTitle=\"Sub Title\" extra={<Button type=\"primary\" text>Link</Button>} />\n <Card.Divider />\n <Card.Content>\n Lorem ipsum dolor sit amet, est viderer iuvaret perfecto et. Ne petentium quaerendum nec, eos ex recteque mediocritatem, ex usu assum legendos temporibus. Ius feugiat pertinacia an, cu verterem praesent quo.\n </Card.Content>\n <Card.Actions>\n <Button type=\"primary\" key=\"action1\" text>Action 1</Button>\n <Button type=\"primary\" key=\"action2\" text>Action 2</Button>\n </Card.Actions>\n </Card>\n </div>\n , mountNode);
.free-card {\n display: inline-block;\n width: 300px;\n vertical-align: top;\n}\n.free-card + .free-card {\n margin-left: 20px;\n}\n\n.free-card.custom {\n display: flex;\n justify-content: space-between;\n width: 500px;\n height: 200px;\n}\n\n.free-card.custom .next-card-media {\n height: 100%;\n width: 200px;\n flex-shrink: 0;\n}\n\n.free-card-main {\n display: flex;\n flex-direction: column;\n align-items: stretch;\n}\n\n.free-card-main .next-card-content-container {\n flex: 1;\n}\n\n.free-card-main .next-card-actions {\n text-align: right;\n}
Hiding head divider by showHeadDivider
.
import { Card } from '@alifd/next';\n\nconst commonProps = {\n title: 'Title',\n style: { width: 300 },\n subTitle: 'Sub-title',\n extra: 'Link'\n};\n\nReactDOM.render(<div>\n <Card {...commonProps} showHeadDivider={false}>\n <div className=\"card-placeholder\"></div>\n </Card>\n</div>, mountNode);
.card-placeholder {\n height: 500px;\n text-align: center;\n background: #F7F8FA;\n}
可以通过设置 showHeadDivider={false}
隐藏头部下划线。
import { Card } from '@alifd/next';\n\nconst commonProps = {\n title: 'Title',\n style: { width: 300 },\n subTitle: 'Sub-title',\n extra: 'Link'\n};\n\nReactDOM.render(<div>\n <Card {...commonProps} showHeadDivider={false}>\n <div className=\"card-placeholder\"></div>\n </Card>\n</div>, mountNode);
.card-placeholder {\n height: 500px;\n text-align: center;\n background: #F7F8FA;\n}
Here is an example of a card that uses images to enhance content.
\n","order":"4"},"codes":{"jsx":"import { Card, Button } from '@alifd/next';\n\nReactDOM.render(\nimport { Card, Button } from '@alifd/next';\n\nReactDOM.render(\n <Card\n className=\"media-card\"\n media={<img src=\"https://img.alicdn.com/tfs/TB1FNIOSFXXXXaWXXXXXXXXXXXX-260-188.png\" />}\n contentHeight=\"auto\"\n title=\"Title\"\n subTitle=\"Sub Title\"\n extra={[\n <Button type=\"primary\" key=\"action1\" text>More</Button>\n ]}\n actions={[\n <Button type=\"primary\" key=\"action1\" text>Action 1</Button>,\n <Button type=\"primary\" key=\"action2\" text>Action 2</Button>\n ]}\n >\n Lorem ipsum dolor sit amet, est viderer iuvaret perfecto et. Ne petentium quaerendum nec, eos ex recteque mediocritatem, ex usu assum legendos temporibus. Ius feugiat pertinacia an, cu verterem praesent quo.\n\n </Card>\n , mountNode);
.media-card {\n width: 300px;\n}\n\n.custom-card p {\n color: #999;\n}
下面是一个使用图像来增强内容的卡片示例。
\n","order":"4"},"codes":{"jsx":"import { Card, Button } from '@alifd/next';\n\nReactDOM.render(\nimport { Card, Button } from '@alifd/next';\n\nReactDOM.render(\n <Card\n className=\"media-card\"\n media={<img src=\"https://img.alicdn.com/tfs/TB1FNIOSFXXXXaWXXXXXXXXXXXX-260-188.png\" />}\n contentHeight=\"auto\"\n title=\"Title\"\n subTitle=\"Sub Title\"\n extra={[\n <Button type=\"primary\" key=\"action1\" text>More</Button>\n ]}\n actions={[\n <Button type=\"primary\" key=\"action1\" text>Action 1</Button>,\n <Button type=\"primary\" key=\"action2\" text>Action 2</Button>\n ]}\n >\n Lorem ipsum dolor sit amet, est viderer iuvaret perfecto et. Ne petentium quaerendum nec, eos ex recteque mediocritatem, ex usu assum legendos temporibus. Ius feugiat pertinacia an, cu verterem praesent quo.\n\n </Card>\n , mountNode);
.media-card {\n width: 300px;\n}\n\n.custom-card p {\n color: #999;\n}
A card is a piece of paper with unique related data taht servers as an entry point to more detailed information.
\nA card could contain a photo, text, and a link about a single subject.
\nParam | \nDescription | \nType | \nDefault Value | \n
---|---|---|---|
title | \nTitle of card | \nString | \n- | \n
subTitle | \nSub title of card | \nString | \n- | \n
showTitleBullet | \nIf show title bullet | \nBoolean | \ntrue | \n
showHeadDivider | \nIf show head divider | \nBoolean | \ntrue | \n
contentHeight | \nHeight of content | \nString/Number | \n120 | \n
extra | \nExtra of card header | \nReactNode | \n- | \n
media | \nMedia content | \nReactNode | \n- | \n
actions | \nActions of card | \nReactNode | \n- | \n
free | \nWhether to open free mode, if opened, can`t set title subTitle ..., must use Card.Header Card.Content ... to set Card | \nBoolean | \n- | \n
参数 | \n说明 | \n类型 | \n默认值 | \n
---|---|---|---|
component | \nThe html tag to be rendered | \ncustom | \n'div' | \n
参数 | \n说明 | \n类型 | \n默认值 | \n
---|---|---|---|
component | \nThe html tag to be rendered | \ncustom | \n'div' | \n
参数 | \n说明 | \n类型 | \n默认值 | \n
---|---|---|---|
component | \nThe html tag to be rendered | \ncustom | \n'hr' | \n
参数 | \n说明 | \n类型 | \n默认值 | \n
---|---|---|---|
title | \nTitle of card | \nReactNode | \n- | \n
subTitle | \nSub Title of Card | \nReactNode | \n- | \n
extra | \nExtra of card header | \nReactNode | \n- | \n
component | \nThe html tag to be rendered | \ncustom | \n'div' | \n
参数 | \n说明 | \n类型 | \n默认值 | \n
---|---|---|---|
component | \nThe html tag to be rendered | \ncustom | \n'div' | \n
image | \nMedia background image | \nString | \n- | \n
src | \nMedia source URL | \nString | \n- | \n
一个通用的卡片组件。
\n当一个模块的同类信息不能自然形成区块感,可借助 Card 组件将信息整合,帮助界面信息模块感更强。
\n参数 | \n说明 | \n类型 | \n默认值 | \n
---|---|---|---|
media | \n卡片的上的图片 / 视频 | \nReactNode | \n- | \n
title | \n卡片的标题 | \nReactNode | \n- | \n
subTitle | \n卡片的副标题 | \nReactNode | \n- | \n
actions | \n卡片操作组,位置在卡片底部 | \nReactNode | \n- | \n
showTitleBullet | \n是否显示标题的项目符号 | \nBoolean | \ntrue | \n
showHeadDivider | \n是否展示头部的分隔线 | \nBoolean | \ntrue | \n
contentHeight | \n内容区域的固定高度 | \nString/Number | \n120 | \n
extra | \n标题区域的用户自定义内容 | \nReactNode | \n- | \n
free | \n是否开启自由模式,开启后card 将使用子组件配合使用, 设置此项后 title, subtitle, 等等属性都将失效 | \nBoolean | \nfalse | \n
参数 | \n说明 | \n类型 | \n默认值 | \n
---|---|---|---|
component | \n设置标签类型 | \ncustom | \n'div' | \n
image | \n背景图片地址 | \nString | \n- | \n
src | \n媒体源文件地址 | \nString | \n- | \n
参数 | \n说明 | \n类型 | \n默认值 | \n
---|---|---|---|
title | \n卡片的标题 | \nReactNode | \n- | \n
subTitle | \n卡片的副标题 | \nReactNode | \n- | \n
extra | \n标题区域的用户自定义内容 | \nReactNode | \n- | \n
component | \n设置标签类型 | \ncustom | \n'div' | \n
参数 | \n说明 | \n类型 | \n默认值 | \n
---|---|---|---|
component | \n设置标签类型 | \ncustom | \n'div' | \n
参数 | \n说明 | \n类型 | \n默认值 | \n
---|---|---|---|
component | \n设置标签类型 | \ncustom | \n'hr' | \n
参数 | \n说明 | \n类型 | \n默认值 | \n
---|---|---|---|
component | \n设置标签类型 | \ncustom | \n'div' | \n
When the developer presses the Enter key to select an item, the screen reader will reads the selection item, which is described by aria-labelledby
.\nPlease refer to ARIA and KeyBoard
for keyboard operation.
import { CascaderSelect } from '@alifd/next';\n\nconst data = [{\n value: '0100',\n label: '金庸',\n children: [\n { value: '0101', label: '飞狐外传' },\n { value: '0102', label: '雪山飞狐' },\n { value: '0103', label: '连城诀' },\n { value: '0104', label: '天龙八部' },\n { value: '0105', label: '射雕英雄传' },\n { value: '0106', label: '白马啸西风' },\n { value: '0107', label: '鹿鼎记' },\n { value: '0108', label: '笑傲江湖' },\n { value: '0109', label: '书剑恩仇录' },\n { value: '0110', label: '神雕侠侣' },\n { value: '0111', label: '侠客行' },\n { value: '0112', label: '倚天屠龙记' },\n { value: '0113', label: '碧血剑' },\n { value: '0114', label: '鸳鸯刀' }\n ]\n}, {\n value: '0200',\n label: '古龙',\n children: [\n { value: '0201', label: '小李飞刀' },\n { value: '0202', label: '绝代双骄' },\n { value: '0203', label: '大旗英雄传' },\n { value: '0204', label: '英雄无泪' },\n { value: '0205', label: '边城浪子' },\n { value: '0206', label: '楚留香传奇' },\n ],\n}, {\n children: [\n { value: '0301', label: '白发魔女传' },\n { value: '0302', label: '七剑下天山' },\n { value: '0303', label: '云海玉弓缘' }\n ],\n value: '0300',\n label: '梁羽生'\n}];\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n this.state = {\n label: '',\n data: []\n };\n this.handleChange = this.handleChange.bind(this);\n }\n componentDidMount() {\n this.setState({ data });\n }\n handleChange(value, data, extra) {\n console.log(value, data, extra);\n\n this.setState({\n label: extra.selectedPath.map(d => d.label).join(' / '), \n });\n }\n render() {\n return (\n <div>\n <div id=\"a11y-cascader-select\" >CascaderSelect: </div>\n <CascaderSelect dataSource={this.state.data} onChange={this.handleChange} listStyle={{ width: '200px', height: '256px' }} aria-labelledby=\"a11y-cascader-select\"/>\n </div>\n );\n }\n}\nReactDOM.render(<Demo />, mountNode);\n
.next-menu-item:focus {\n background-color: #F2F3F7;\n}
当聚焦在组件上时,通过aria-labelledby
对组件进行描述。关于键盘操作请参考ARIA and KeyBoard
。
import { CascaderSelect } from '@alifd/next';\n\nconst data = [{\n value: '0100',\n label: '金庸',\n children: [\n { value: '0101', label: '飞狐外传' },\n { value: '0102', label: '雪山飞狐' },\n { value: '0103', label: '连城诀' },\n { value: '0104', label: '天龙八部' },\n { value: '0105', label: '射雕英雄传' },\n { value: '0106', label: '白马啸西风' },\n { value: '0107', label: '鹿鼎记' },\n { value: '0108', label: '笑傲江湖' },\n { value: '0109', label: '书剑恩仇录' },\n { value: '0110', label: '神雕侠侣' },\n { value: '0111', label: '侠客行' },\n { value: '0112', label: '倚天屠龙记' },\n { value: '0113', label: '碧血剑' },\n { value: '0114', label: '鸳鸯刀' }\n ]\n}, {\n value: '0200',\n label: '古龙',\n children: [\n { value: '0201', label: '小李飞刀' },\n { value: '0202', label: '绝代双骄' },\n { value: '0203', label: '大旗英雄传' },\n { value: '0204', label: '英雄无泪' },\n { value: '0205', label: '边城浪子' },\n { value: '0206', label: '楚留香传奇' },\n ],\n}, {\n children: [\n { value: '0301', label: '白发魔女传' },\n { value: '0302', label: '七剑下天山' },\n { value: '0303', label: '云海玉弓缘' }\n ],\n value: '0300',\n label: '梁羽生'\n}];\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n this.state = {\n label: '',\n data: []\n };\n this.handleChange = this.handleChange.bind(this);\n }\n componentDidMount() {\n this.setState({ data });\n }\n handleChange(value, data, extra) {\n console.log(value, data, extra);\n\n this.setState({\n label: extra.selectedPath.map(d => d.label).join(' / '), \n });\n }\n render() {\n return (\n <div>\n <div id=\"a11y-cascader-select\" >CascaderSelect: </div>\n <CascaderSelect dataSource={this.state.data} onChange={this.handleChange} listStyle={{ width: '200px', height: '256px' }} aria-labelledby=\"a11y-cascader-select\"/>\n </div>\n );\n }\n}\nReactDOM.render(<Demo />, mountNode);\n
.next-menu-item:focus {\n background-color: #F2F3F7;\n}
Demo the basic single select usage.
\n","order":"0"},"codes":{"jsx":"import { CascaderSelect } from '@alifd/next';\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n data: []\n };\n\n this.handleChange = this.handleChange.bind(this);\n }\n\n componentDidMount() {\n fetch('https://os.alipayobjects.com/rmsportal/ODDwqcDFTLAguOvWEolX.json')\n .then(response => response.json())\n .then(data => {\n data[1].disabled = true;\n this.setState({ data });\n })\n .catch(e => console.log(e));\n }\n\n handleChange(value, data, extra) {\n console.log(value, data, extra);\n }\n\n render() {\n returnimport { CascaderSelect } from '@alifd/next';\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n data: []\n };\n\n this.handleChange = this.handleChange.bind(this);\n }\n\n componentDidMount() {\n fetch('https://os.alipayobjects.com/rmsportal/ODDwqcDFTLAguOvWEolX.json')\n .then(response => response.json())\n .then(data => {\n data[1].disabled = true;\n this.setState({ data });\n })\n .catch(e => console.log(e));\n }\n\n handleChange(value, data, extra) {\n console.log(value, data, extra);\n }\n\n render() {\n return <CascaderSelect style={{ width: '302px' }} dataSource={this.state.data} onChange={this.handleChange} />;\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
展示基本的单选用法。
\n","order":"0"},"codes":{"jsx":"import { CascaderSelect } from '@alifd/next';\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n data: []\n };\n\n this.handleChange = this.handleChange.bind(this);\n }\n\n componentDidMount() {\n fetch('https://os.alipayobjects.com/rmsportal/ODDwqcDFTLAguOvWEolX.json')\n .then(response => response.json())\n .then(data => {\n data[1].disabled = true;\n this.setState({ data });\n })\n .catch(e => console.log(e));\n }\n\n handleChange(value, data, extra) {\n console.log(value, data, extra);\n }\n\n render() {\n returnimport { CascaderSelect } from '@alifd/next';\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n data: []\n };\n\n this.handleChange = this.handleChange.bind(this);\n }\n\n componentDidMount() {\n fetch('https://os.alipayobjects.com/rmsportal/ODDwqcDFTLAguOvWEolX.json')\n .then(response => response.json())\n .then(data => {\n data[1].disabled = true;\n this.setState({ data });\n })\n .catch(e => console.log(e));\n }\n\n handleChange(value, data, extra) {\n console.log(value, data, extra);\n }\n\n render() {\n return <CascaderSelect style={{ width: '302px' }} dataSource={this.state.data} onChange={this.handleChange} />;\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
You can use displayRender to customize the results displayed when single select, and you can customize the component width and height by using listStyle and listClassName.
\n","order":"6"},"codes":{"jsx":"import { CascaderSelect, Icon } from '@alifd/next';\n\nconst dataSource = [{\n value: '2973',\n label: '陕西',\n children: [{\n value: '2974',\n label: '西安',\n children: [\n { value: '2975', label: '西安市' },\n { value: '2976', label: '高陵县' }\n ]\n }, {\n value: '2980',\n label: '铜川',\n children: [\n { value: '2981', label: '铜川市' },\n { value: '2982', label: '宜君县' }\n ]\n }]\n}, {\n value: '3371',\n label: '新疆',\n children: [{\n value: '3430',\n label: '巴音郭楞蒙古自治州',\n children: [\n { value: '3431', label: '库尔勒市' },\n { value: '3432', label: '和静县' }\n ]\n }]\n}];\n\nconst itemRender = item => {\n return (\n \nimport { CascaderSelect, Icon } from '@alifd/next';\n\nconst dataSource = [{\n value: '2973',\n label: '陕西',\n children: [{\n value: '2974',\n label: '西安',\n children: [\n { value: '2975', label: '西安市' },\n { value: '2976', label: '高陵县' }\n ]\n }, {\n value: '2980',\n label: '铜川',\n children: [\n { value: '2981', label: '铜川市' },\n { value: '2982', label: '宜君县' }\n ]\n }]\n}, {\n value: '3371',\n label: '新疆',\n children: [{\n value: '3430',\n label: '巴音郭楞蒙古自治州',\n children: [\n { value: '3431', label: '库尔勒市' },\n { value: '3432', label: '和静县' }\n ]\n }]\n}];\n\nconst itemRender = item => {\n return (\n <span>\n <Icon type=\"account\" size=\"xs\" /> {item.label}\n </span>\n );\n};\n\nReactDOM.render(<CascaderSelect style={{ width: '452px'}} listStyle={{ width: '150px', height: '160px' }} displayRender={labels => labels[labels.length - 1]} defaultValue=\"3431\" dataSource={dataSource} itemRender={itemRender} />, mountNode);
可以通过 displayRender 来定制单选时展示的结果,可以通过 listStyle,listClassName 来定制组件宽高。
\n","order":"6"},"codes":{"jsx":"import { CascaderSelect, Icon } from '@alifd/next';\n\nconst dataSource = [{\n value: '2973',\n label: '陕西',\n children: [{\n value: '2974',\n label: '西安',\n children: [\n { value: '2975', label: '西安市' },\n { value: '2976', label: '高陵县' }\n ]\n }, {\n value: '2980',\n label: '铜川',\n children: [\n { value: '2981', label: '铜川市' },\n { value: '2982', label: '宜君县' }\n ]\n }]\n}, {\n value: '3371',\n label: '新疆',\n children: [{\n value: '3430',\n label: '巴音郭楞蒙古自治州',\n children: [\n { value: '3431', label: '库尔勒市' },\n { value: '3432', label: '和静县' }\n ]\n }]\n}];\n\nconst itemRender = item => {\n return (\n \nimport { CascaderSelect, Icon } from '@alifd/next';\n\nconst dataSource = [{\n value: '2973',\n label: '陕西',\n children: [{\n value: '2974',\n label: '西安',\n children: [\n { value: '2975', label: '西安市' },\n { value: '2976', label: '高陵县' }\n ]\n }, {\n value: '2980',\n label: '铜川',\n children: [\n { value: '2981', label: '铜川市' },\n { value: '2982', label: '宜君县' }\n ]\n }]\n}, {\n value: '3371',\n label: '新疆',\n children: [{\n value: '3430',\n label: '巴音郭楞蒙古自治州',\n children: [\n { value: '3431', label: '库尔勒市' },\n { value: '3432', label: '和静县' }\n ]\n }]\n}];\n\nconst itemRender = item => {\n return (\n <span>\n <Icon type=\"account\" size=\"xs\" /> {item.label}\n </span>\n );\n};\n\nReactDOM.render(<CascaderSelect style={{ width: '452px'}} listStyle={{ width: '150px', height: '160px' }} displayRender={labels => labels[labels.length - 1]} defaultValue=\"3431\" dataSource={dataSource} itemRender={itemRender} />, mountNode);
import { CascaderSelect } from '@alifd/next';\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n data: []\n };\n\n this.handleChange = this.handleChange.bind(this);\n }\n\n componentDidMount() {\n fetch('https://os.alipayobjects.com/rmsportal/ODDwqcDFTLAguOvWEolX.json')\n .then(response => response.json())\n .then(data => {\n data[1].disabled = true;\n this.setState({ data });\n })\n .catch(e => console.log(e));\n }\n\n handleChange(value, data, extra) {\n console.log(value, data, extra);\n }\n\n valueRender = (item) => {\n if (item.label) {\n return item.label; // 正常的item\n }\n\n // value在 dataSouce里不存在时渲染。\n return item.value === '432988' ? '不存在的' : item.value;\n };\n\n render() {\n return <CascaderSelect valueRender={this.valueRender} defaultValue=\"432988\" style={{ width: '302px' }} dataSource={this.state.data} onChange={this.handleChange} />;\n }\n}\nReactDOM.render(<Demo />, mountNode);
Demon loading data asynchronously.
\n","order":"7"},"codes":{"jsx":"import { CascaderSelect } from '@alifd/next';\n\nconst dataSource = [{\n value: '2973',\n label: '陕西'\n}];\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n dataSource\n };\n\n this.onLoadData = this.onLoadData.bind(this);\n }\n\n onLoadData(data) {\n console.log(data);\n\n return new Promise(resolve => {\n setTimeout(() => {\n this.setState({\n dataSource: [{\n value: '2973',\n label: '陕西',\n children: [{\n value: '2974',\n label: '西安',\n children: [\n { value: '2975', label: '西安市', isLeaf: true },\n { value: '2976', label: '高陵县', isLeaf: true }\n ]\n }, {\n value: '2980',\n label: '铜川',\n children: [\n { value: '2981', label: '铜川市', isLeaf: true },\n { value: '2982', label: '宜君县', isLeaf: true }\n ]\n }]\n }]\n }, resolve);\n }, 500);\n });\n }\n\n render() {\n returnimport { CascaderSelect } from '@alifd/next';\n\nconst dataSource = [{\n value: '2973',\n label: '陕西'\n}];\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n dataSource\n };\n\n this.onLoadData = this.onLoadData.bind(this);\n }\n\n onLoadData(data) {\n console.log(data);\n\n return new Promise(resolve => {\n setTimeout(() => {\n this.setState({\n dataSource: [{\n value: '2973',\n label: '陕西',\n children: [{\n value: '2974',\n label: '西安',\n children: [\n { value: '2975', label: '西安市', isLeaf: true },\n { value: '2976', label: '高陵县', isLeaf: true }\n ]\n }, {\n value: '2980',\n label: '铜川',\n children: [\n { value: '2981', label: '铜川市', isLeaf: true },\n { value: '2982', label: '宜君县', isLeaf: true }\n ]\n }]\n }]\n }, resolve);\n }, 500);\n });\n }\n\n render() {\n return <CascaderSelect style={{ width: '302px' }} dataSource={this.state.dataSource} loadData={this.onLoadData} />;\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
展示动态获取数据的用法。
\n","order":"7"},"codes":{"jsx":"import { CascaderSelect } from '@alifd/next';\n\nconst dataSource = [{\n value: '2973',\n label: '陕西'\n}];\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n dataSource\n };\n\n this.onLoadData = this.onLoadData.bind(this);\n }\n\n onLoadData(data) {\n console.log(data);\n\n return new Promise(resolve => {\n setTimeout(() => {\n this.setState({\n dataSource: [{\n value: '2973',\n label: '陕西',\n children: [{\n value: '2974',\n label: '西安',\n children: [\n { value: '2975', label: '西安市', isLeaf: true },\n { value: '2976', label: '高陵县', isLeaf: true }\n ]\n }, {\n value: '2980',\n label: '铜川',\n children: [\n { value: '2981', label: '铜川市', isLeaf: true },\n { value: '2982', label: '宜君县', isLeaf: true }\n ]\n }]\n }]\n }, resolve);\n }, 500);\n });\n }\n\n render() {\n returnimport { CascaderSelect } from '@alifd/next';\n\nconst dataSource = [{\n value: '2973',\n label: '陕西'\n}];\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n dataSource\n };\n\n this.onLoadData = this.onLoadData.bind(this);\n }\n\n onLoadData(data) {\n console.log(data);\n\n return new Promise(resolve => {\n setTimeout(() => {\n this.setState({\n dataSource: [{\n value: '2973',\n label: '陕西',\n children: [{\n value: '2974',\n label: '西安',\n children: [\n { value: '2975', label: '西安市', isLeaf: true },\n { value: '2976', label: '高陵县', isLeaf: true }\n ]\n }, {\n value: '2980',\n label: '铜川',\n children: [\n { value: '2981', label: '铜川市', isLeaf: true },\n { value: '2982', label: '宜君县', isLeaf: true }\n ]\n }]\n }]\n }, resolve);\n }, 500);\n });\n }\n\n render() {\n return <CascaderSelect style={{ width: '302px' }} dataSource={this.state.dataSource} loadData={this.onLoadData} />;\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
You can set expand trigger type by setting expandTriggerType
, support click
and hover
, the default is click
.
import { Radio, CascaderSelect } from '@alifd/next';\n\nconst RadioGroup = Radio.Group;\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n triggerType: 'click',\n data: []\n };\n\n this.handleChange = this.handleChange.bind(this);\n this.handleTriggerTypeChange = this.handleTriggerTypeChange.bind(this);\n }\n\n componentDidMount() {\n fetch('https://os.alipayobjects.com/rmsportal/ODDwqcDFTLAguOvWEolX.json')\n .then(response => response.json())\n .then(data => this.setState({ data }))\n .catch(e => console.log(e));\n }\n\n handleChange(value, data, extra) {\n console.log(value, data, extra);\n }\n\n handleTriggerTypeChange(triggerType) {\n this.setState({\n triggerType\n });\n }\n\n render() {\n return (\n <div>\n <div className=\"trigger-check\">\n Expand trigger type:\n <RadioGroup dataSource={['click', 'hover']} value={this.state.triggerType} onChange={this.handleTriggerTypeChange} />\n </div>\n\n <CascaderSelect style={{ width: '302px' }} expandTriggerType={this.state.triggerType} dataSource={this.state.data} onChange={this.handleChange} />\n </div>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
.trigger-check {\n margin-bottom: 10px;\n font-size: 14px;\n color: #666;\n}\n\n.trigger-check .next-radio-group {\n margin-left: 10px;\n}
展示可通过 expandTriggerType 来设置不同的展开触发行为,支持 click 和 hover,默认值为 click。
\n","order":"1"},"codes":{"jsx":"import { Radio, CascaderSelect } from '@alifd/next';\n\nconst RadioGroup = Radio.Group;\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n triggerType: 'click',\n data: []\n };\n\n this.handleChange = this.handleChange.bind(this);\n this.handleTriggerTypeChange = this.handleTriggerTypeChange.bind(this);\n }\n\n componentDidMount() {\n fetch('https://os.alipayobjects.com/rmsportal/ODDwqcDFTLAguOvWEolX.json')\n .then(response => response.json())\n .then(data => this.setState({ data }))\n .catch(e => console.log(e));\n }\n\n handleChange(value, data, extra) {\n console.log(value, data, extra);\n }\n\n handleTriggerTypeChange(triggerType) {\n this.setState({\n triggerType\n });\n }\n\n render() {\n return (\nimport { Radio, CascaderSelect } from '@alifd/next';\n\nconst RadioGroup = Radio.Group;\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n triggerType: 'click',\n data: []\n };\n\n this.handleChange = this.handleChange.bind(this);\n this.handleTriggerTypeChange = this.handleTriggerTypeChange.bind(this);\n }\n\n componentDidMount() {\n fetch('https://os.alipayobjects.com/rmsportal/ODDwqcDFTLAguOvWEolX.json')\n .then(response => response.json())\n .then(data => this.setState({ data }))\n .catch(e => console.log(e));\n }\n\n handleChange(value, data, extra) {\n console.log(value, data, extra);\n }\n\n handleTriggerTypeChange(triggerType) {\n this.setState({\n triggerType\n });\n }\n\n render() {\n return (\n <div>\n <div className=\"trigger-check\">\n Expand trigger type:\n <RadioGroup dataSource={['click', 'hover']} value={this.state.triggerType} onChange={this.handleTriggerTypeChange} />\n </div>\n\n <CascaderSelect style={{ width: '302px' }} expandTriggerType={this.state.triggerType} dataSource={this.state.data} onChange={this.handleChange} />\n </div>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
.trigger-check {\n margin-bottom: 10px;\n font-size: 14px;\n color: #666;\n}\n\n.trigger-check .next-radio-group {\n margin-left: 10px;\n}
Demo whether parent and child nodes checked is related.
\n","order":"4"},"codes":{"jsx":"import { Checkbox, CascaderSelect } from '@alifd/next';\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n value: [],\n data: [],\n checkStrictly: false\n };\n\n this.handleCheck = this.handleCheck.bind(this);\n this.handleChange = this.handleChange.bind(this);\n }\n\n componentDidMount() {\n fetch('https://os.alipayobjects.com/rmsportal/ODDwqcDFTLAguOvWEolX.json')\n .then(response => response.json())\n .then(data => this.setState({ data, value: ['2975'] }))\n .catch(e => console.log(e));\n }\n\n handleCheck() {\n this.setState({\n checkStrictly: !this.state.checkStrictly,\n value: []\n });\n }\n\n handleChange(value, data, extra) {\n console.log(value, data, extra);\n\n this.setState({\n value\n });\n }\n\n render() {\n return (\nimport { Checkbox, CascaderSelect } from '@alifd/next';\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n value: [],\n data: [],\n checkStrictly: false\n };\n\n this.handleCheck = this.handleCheck.bind(this);\n this.handleChange = this.handleChange.bind(this);\n }\n\n componentDidMount() {\n fetch('https://os.alipayobjects.com/rmsportal/ODDwqcDFTLAguOvWEolX.json')\n .then(response => response.json())\n .then(data => this.setState({ data, value: ['2975'] }))\n .catch(e => console.log(e));\n }\n\n handleCheck() {\n this.setState({\n checkStrictly: !this.state.checkStrictly,\n value: []\n });\n }\n\n handleChange(value, data, extra) {\n console.log(value, data, extra);\n\n this.setState({\n value\n });\n }\n\n render() {\n return (\n <div className=\"control-multiple-demo\">\n <label className=\"strictly-check\">\n <Checkbox value={this.state.checkStrictly} onChange={this.handleCheck} />\n <span className=\"strictly-text\">Enable checkStrictly</span>\n </label>\n <CascaderSelect style={{ width: '302px' }} multiple checkStrictly={this.state.checkStrictly} value={this.state.value} dataSource={this.state.data} onChange={this.handleChange} />\n </div>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
.control-multiple-demo .strictly-check {\n display: block;\n margin-bottom: 10px;\n}\n\n.control-multiple-demo .strictly-text {\n display: inline-block;\n margin-left: 10px;\n vertical-align: middle;\n color: #666;\n font-size: 14px;\n}
展示受控多选以及是否开启严格受控父子节点选中不再关联的用法。
\n","order":"4"},"codes":{"jsx":"import { Checkbox, CascaderSelect } from '@alifd/next';\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n value: [],\n data: [],\n checkStrictly: false\n };\n\n this.handleCheck = this.handleCheck.bind(this);\n this.handleChange = this.handleChange.bind(this);\n }\n\n componentDidMount() {\n fetch('https://os.alipayobjects.com/rmsportal/ODDwqcDFTLAguOvWEolX.json')\n .then(response => response.json())\n .then(data => this.setState({ data, value: ['2975'] }))\n .catch(e => console.log(e));\n }\n\n handleCheck() {\n this.setState({\n checkStrictly: !this.state.checkStrictly,\n value: []\n });\n }\n\n handleChange(value, data, extra) {\n console.log(value, data, extra);\n\n this.setState({\n value\n });\n }\n\n render() {\n return (\nimport { Checkbox, CascaderSelect } from '@alifd/next';\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n value: [],\n data: [],\n checkStrictly: false\n };\n\n this.handleCheck = this.handleCheck.bind(this);\n this.handleChange = this.handleChange.bind(this);\n }\n\n componentDidMount() {\n fetch('https://os.alipayobjects.com/rmsportal/ODDwqcDFTLAguOvWEolX.json')\n .then(response => response.json())\n .then(data => this.setState({ data, value: ['2975'] }))\n .catch(e => console.log(e));\n }\n\n handleCheck() {\n this.setState({\n checkStrictly: !this.state.checkStrictly,\n value: []\n });\n }\n\n handleChange(value, data, extra) {\n console.log(value, data, extra);\n\n this.setState({\n value\n });\n }\n\n render() {\n return (\n <div className=\"control-multiple-demo\">\n <label className=\"strictly-check\">\n <Checkbox value={this.state.checkStrictly} onChange={this.handleCheck} />\n <span className=\"strictly-text\">Enable checkStrictly</span>\n </label>\n <CascaderSelect style={{ width: '302px' }} multiple checkStrictly={this.state.checkStrictly} value={this.state.value} dataSource={this.state.data} onChange={this.handleChange} />\n </div>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
.control-multiple-demo .strictly-check {\n display: block;\n margin-bottom: 10px;\n}\n\n.control-multiple-demo .strictly-text {\n display: inline-block;\n margin-left: 10px;\n vertical-align: middle;\n color: #666;\n font-size: 14px;\n}
Demo the basic multiple select usage.
\n","order":"2"},"codes":{"jsx":"import { CascaderSelect } from '@alifd/next';\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n data: []\n };\n\n this.handleChange = this.handleChange.bind(this);\n }\n\n componentDidMount() {\n fetch('https://os.alipayobjects.com/rmsportal/ODDwqcDFTLAguOvWEolX.json')\n .then(response => response.json())\n .then(data => {\n data[1].disabled = true;\n data[2].checkboxDisabled = true;\n this.setState({ data });\n })\n .catch(e => console.log(e));\n }\n\n handleChange(value, data, extra) {\n console.log(value, data, extra);\n }\n\n render() {\n returnimport { CascaderSelect } from '@alifd/next';\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n data: []\n };\n\n this.handleChange = this.handleChange.bind(this);\n }\n\n componentDidMount() {\n fetch('https://os.alipayobjects.com/rmsportal/ODDwqcDFTLAguOvWEolX.json')\n .then(response => response.json())\n .then(data => {\n data[1].disabled = true;\n data[2].checkboxDisabled = true;\n this.setState({ data });\n })\n .catch(e => console.log(e));\n }\n\n handleChange(value, data, extra) {\n console.log(value, data, extra);\n }\n\n render() {\n return <CascaderSelect style={{ width: '302px' }} multiple dataSource={this.state.data} onChange={this.handleChange} />;\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
.cascader-value {\n width: 500px;\n margin-bottom: 10px;\n font-size: 14px;\n color: #666;\n}
展示基本的多选用法。
\n","order":"2"},"codes":{"jsx":"import { CascaderSelect } from '@alifd/next';\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n data: []\n };\n\n this.handleChange = this.handleChange.bind(this);\n }\n\n componentDidMount() {\n fetch('https://os.alipayobjects.com/rmsportal/ODDwqcDFTLAguOvWEolX.json')\n .then(response => response.json())\n .then(data => {\n data[1].disabled = true;\n data[2].checkboxDisabled = true;\n this.setState({ data });\n })\n .catch(e => console.log(e));\n }\n\n handleChange(value, data, extra) {\n console.log(value, data, extra);\n }\n\n render() {\n returnimport { CascaderSelect } from '@alifd/next';\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n data: []\n };\n\n this.handleChange = this.handleChange.bind(this);\n }\n\n componentDidMount() {\n fetch('https://os.alipayobjects.com/rmsportal/ODDwqcDFTLAguOvWEolX.json')\n .then(response => response.json())\n .then(data => {\n data[1].disabled = true;\n data[2].checkboxDisabled = true;\n this.setState({ data });\n })\n .catch(e => console.log(e));\n }\n\n handleChange(value, data, extra) {\n console.log(value, data, extra);\n }\n\n render() {\n return <CascaderSelect style={{ width: '302px' }} multiple dataSource={this.state.data} onChange={this.handleChange} />;\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
.cascader-value {\n width: 500px;\n margin-bottom: 10px;\n font-size: 14px;\n color: #666;\n}
You can enable search by setting showSearch to true.
\n","order":"5"},"codes":{"jsx":"import { Checkbox, CascaderSelect } from '@alifd/next';\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n value: [],\n data: [],\n multiple: false\n };\n\n this.handleCheck = this.handleCheck.bind(this);\n this.handleChange = this.handleChange.bind(this);\n }\n\n componentDidMount() {\n fetch('https://os.alipayobjects.com/rmsportal/ODDwqcDFTLAguOvWEolX.json')\n .then(response => response.json())\n .then(data => this.setState({ data, value: ['2975'] }))\n .catch(e => console.log(e));\n }\n\n handleCheck() {\n this.setState({\n multiple: !this.state.multiple,\n value: []\n });\n }\n\n handleChange(value, data, extra) {\n console.log(value, data, extra);\n\n this.setState({\n value\n });\n }\n\n render() {\n return (\nimport { Checkbox, CascaderSelect } from '@alifd/next';\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n value: [],\n data: [],\n multiple: false\n };\n\n this.handleCheck = this.handleCheck.bind(this);\n this.handleChange = this.handleChange.bind(this);\n }\n\n componentDidMount() {\n fetch('https://os.alipayobjects.com/rmsportal/ODDwqcDFTLAguOvWEolX.json')\n .then(response => response.json())\n .then(data => this.setState({ data, value: ['2975'] }))\n .catch(e => console.log(e));\n }\n\n handleCheck() {\n this.setState({\n multiple: !this.state.multiple,\n value: []\n });\n }\n\n handleChange(value, data, extra) {\n console.log(value, data, extra);\n\n this.setState({\n value\n });\n }\n\n render() {\n return (\n <div className=\"search-demo\">\n <label className=\"multiple-check\">\n <Checkbox value={this.state.multiple} onChange={this.handleCheck} />\n <span className=\"multiple-text\">Multiple select</span>\n </label>\n <CascaderSelect style={{ width: '302px' }} showSearch multiple={this.state.multiple} value={this.state.value} dataSource={this.state.data} onChange={this.handleChange} />\n </div>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
.search-demo .multiple-check {\n display: block;\n margin-bottom: 10px;\n}\n\n.search-demo .multiple-text {\n display: inline-block;\n margin-left: 10px;\n vertical-align: middle;\n color: #666;\n font-size: 14px;\n}
通过设置 showSearch 为 true,可以开启组件的搜索功能。
\n","order":"5"},"codes":{"jsx":"import { Checkbox, CascaderSelect } from '@alifd/next';\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n value: [],\n data: [],\n multiple: false\n };\n\n this.handleCheck = this.handleCheck.bind(this);\n this.handleChange = this.handleChange.bind(this);\n }\n\n componentDidMount() {\n fetch('https://os.alipayobjects.com/rmsportal/ODDwqcDFTLAguOvWEolX.json')\n .then(response => response.json())\n .then(data => this.setState({ data, value: ['2975'] }))\n .catch(e => console.log(e));\n }\n\n handleCheck() {\n this.setState({\n multiple: !this.state.multiple,\n value: []\n });\n }\n\n handleChange(value, data, extra) {\n console.log(value, data, extra);\n\n this.setState({\n value\n });\n }\n\n render() {\n return (\nimport { Checkbox, CascaderSelect } from '@alifd/next';\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n value: [],\n data: [],\n multiple: false\n };\n\n this.handleCheck = this.handleCheck.bind(this);\n this.handleChange = this.handleChange.bind(this);\n }\n\n componentDidMount() {\n fetch('https://os.alipayobjects.com/rmsportal/ODDwqcDFTLAguOvWEolX.json')\n .then(response => response.json())\n .then(data => this.setState({ data, value: ['2975'] }))\n .catch(e => console.log(e));\n }\n\n handleCheck() {\n this.setState({\n multiple: !this.state.multiple,\n value: []\n });\n }\n\n handleChange(value, data, extra) {\n console.log(value, data, extra);\n\n this.setState({\n value\n });\n }\n\n render() {\n return (\n <div className=\"search-demo\">\n <label className=\"multiple-check\">\n <Checkbox value={this.state.multiple} onChange={this.handleCheck} />\n <span className=\"multiple-text\">Multiple select</span>\n </label>\n <CascaderSelect style={{ width: '302px' }} showSearch multiple={this.state.multiple} value={this.state.value} dataSource={this.state.data} onChange={this.handleChange} />\n </div>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
.search-demo .multiple-check {\n display: block;\n margin-bottom: 10px;\n}\n\n.search-demo .multiple-text {\n display: inline-block;\n margin-left: 10px;\n vertical-align: middle;\n color: #666;\n font-size: 14px;\n}
Demo the controlled single select and whether it can only select leaf items.
\n","order":"3"},"codes":{"jsx":"import { Checkbox, CascaderSelect } from '@alifd/next';\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n value: null,\n changeOnSelect: false,\n data: []\n };\n\n this.handleCheck = this.handleCheck.bind(this);\n this.handleChange = this.handleChange.bind(this);\n }\n\n componentDidMount() {\n fetch('https://os.alipayobjects.com/rmsportal/ODDwqcDFTLAguOvWEolX.json')\n .then(response => response.json())\n .then(data => this.setState({ data, value: '2975' }))\n .catch(e => console.log(e));\n }\n\n handleCheck() {\n this.setState({\n changeOnSelect: !this.state.changeOnSelect,\n value: null\n });\n }\n\n handleChange(value, data, extra) {\n console.log(value, data, extra);\n\n this.setState({\n value\n });\n }\n\n render() {\n return (\nimport { Checkbox, CascaderSelect } from '@alifd/next';\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n value: null,\n changeOnSelect: false,\n data: []\n };\n\n this.handleCheck = this.handleCheck.bind(this);\n this.handleChange = this.handleChange.bind(this);\n }\n\n componentDidMount() {\n fetch('https://os.alipayobjects.com/rmsportal/ODDwqcDFTLAguOvWEolX.json')\n .then(response => response.json())\n .then(data => this.setState({ data, value: '2975' }))\n .catch(e => console.log(e));\n }\n\n handleCheck() {\n this.setState({\n changeOnSelect: !this.state.changeOnSelect,\n value: null\n });\n }\n\n handleChange(value, data, extra) {\n console.log(value, data, extra);\n\n this.setState({\n value\n });\n }\n\n render() {\n return (\n <div className=\"control-single-demo\">\n <label className=\"change-check\">\n <Checkbox value={!this.state.changeOnSelect} onChange={this.handleCheck} />\n <span className=\"change-text\">Enable changeOnSelect</span>\n </label>\n <CascaderSelect style={{ width: '302px' }} changeOnSelect={this.state.changeOnSelect} value={this.state.value} dataSource={this.state.data} onChange={this.handleChange} />\n </div>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
.control-single-demo .change-check {\n display: block;\n margin-bottom: 10px;\n}\n\n.control-single-demo .change-text {\n display: inline-block;\n margin-left: 10px;\n vertical-align: middle;\n color: #666;\n font-size: 14px;\n}
展示受控单选以及是否选择即改变。
\n","order":"3"},"codes":{"jsx":"import { Checkbox, CascaderSelect } from '@alifd/next';\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n value: null,\n changeOnSelect: false,\n data: []\n };\n\n this.handleCheck = this.handleCheck.bind(this);\n this.handleChange = this.handleChange.bind(this);\n }\n\n componentDidMount() {\n fetch('https://os.alipayobjects.com/rmsportal/ODDwqcDFTLAguOvWEolX.json')\n .then(response => response.json())\n .then(data => this.setState({ data, value: '2975' }))\n .catch(e => console.log(e));\n }\n\n handleCheck() {\n this.setState({\n changeOnSelect: !this.state.changeOnSelect,\n value: null\n });\n }\n\n handleChange(value, data, extra) {\n console.log(value, data, extra);\n\n this.setState({\n value\n });\n }\n\n render() {\n return (\nimport { Checkbox, CascaderSelect } from '@alifd/next';\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n value: null,\n changeOnSelect: false,\n data: []\n };\n\n this.handleCheck = this.handleCheck.bind(this);\n this.handleChange = this.handleChange.bind(this);\n }\n\n componentDidMount() {\n fetch('https://os.alipayobjects.com/rmsportal/ODDwqcDFTLAguOvWEolX.json')\n .then(response => response.json())\n .then(data => this.setState({ data, value: '2975' }))\n .catch(e => console.log(e));\n }\n\n handleCheck() {\n this.setState({\n changeOnSelect: !this.state.changeOnSelect,\n value: null\n });\n }\n\n handleChange(value, data, extra) {\n console.log(value, data, extra);\n\n this.setState({\n value\n });\n }\n\n render() {\n return (\n <div className=\"control-single-demo\">\n <label className=\"change-check\">\n <Checkbox value={!this.state.changeOnSelect} onChange={this.handleCheck} />\n <span className=\"change-text\">Enable changeOnSelect</span>\n </label>\n <CascaderSelect style={{ width: '302px' }} changeOnSelect={this.state.changeOnSelect} value={this.state.value} dataSource={this.state.data} onChange={this.handleChange} />\n </div>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
.control-single-demo .change-check {\n display: block;\n margin-bottom: 10px;\n}\n\n.control-single-demo .change-text {\n display: inline-block;\n margin-left: 10px;\n vertical-align: middle;\n color: #666;\n font-size: 14px;\n}
CascaderSelect consists of Select and Cascader. Cascader are hidden in a pop up layer by default and are mostly used in form scenes.
\nParam | \nDescription | \nType | \nDefault Value | \n
---|---|---|---|
size | \nsize of selector options: 'small', 'medium', 'large' | \nEnum | \n'medium' | \n
placeholder | \nplaceholder of selector | \nString | \n- | \n
disabled | \nwhether is disabled | \nBoolean | \nfalse | \n
hasArrow | \nwhether has arrow icon | \nBoolean | \ntrue | \n
hasBorder | \nwhether selector has border | \nBoolean | \ntrue | \n
hasClear | \nwhether has clear button | \nBoolean | \nfalse | \n
label | \ncustom inline label | \nReactNode | \n- | \n
readOnly | \nwhether selector is read only, it can be expanded but cannot be selected under read only mode | \nBoolean | \n- | \n
dataSource | \ndata source, structure can refer to the following document | \nArray<Object> | \n[] | \n
defaultValue | \n(under uncontrol) default value | \nString/Array<String> | \nnull | \n
value | \n(under control) current value | \nString/Array<String> | \n- | \n
onChange | \ncallback triggered when value changes signatures: Function(value: String/Array, data: Object/Array, extra: Object) => void params: value: {String/Array} selected value, a single value is returned when single select, and an array is returned when multiple select data: {Object/Array} selected data, including value, label, returns a single value when single select, returns an array when multiple select, parent and child nodes are selected at the same time, only the parent node is returned extra: {Object} extra param extra.selectedPath: {Array} path of the selected data when single selecte extra.checked: {Boolean} whether is checked when multiple select extra.currentData: {Object} current operation data when multiple select extra.checkedData: {Array} all checked data when multiple select extra.indeterminateData: {Array} indeterminate data when multile selec | \nFunction | \n- | \n
defaultExpandedValue | \n(under uncontrol) default expanded value, if not set, the component will be automatically set according to defaultValue/value | \nArray<String> | \n- | \n
expandTriggerType | \nexpand trigger type options: 'click', 'hover' | \nEnum | \n'click' | \n
multiple | \nwhether is multiple select | \nBoolean | \nfalse | \n
changeOnSelect | \nchange immediately if selected, this property is only worked in single selection mode | \nBoolean | \nfalse | \n
canOnlyCheckLeaf | \nwhether checkbox of leaf item can only be checked, this property is only worked in multiple selection mode | \nBoolean | \nfalse | \n
checkStrictly | \nwhether selection of parent and child nodes are related | \nBoolean | \nfalse | \n
listStyle | \nstyle of list | \nObject | \n- | \n
listClassName | \nclass name of list | \nString | \n- | \n
displayRender | \ncustom rendering function to display results signatures: Function(label: Array) => ReactNode params: label: {Array} label array of the selected path returns: {ReactNode} display content | \nFunction | \nsingle select: labelPath => labelPath.join(' / '); multiple select: labelPath => labelPath[labelPath.length - 1] | \n
showSearch | \nwhether to show the search box | \nBoolean | \nfalse | \n
filter | \ncustom search function signatures: Function(searchValue: String, path: Array) => Boolean params: searchValue: {String} search keyword path: {Array} item path returns: {Boolean} whether is matched | \nFunction | \nfuzzy matching of label based on all nodes of the path | \n
resultRender | \ncustom render function of search result signatures: Function(searchValue: String, path: Array) => ReactNode params: searchValue: {String} search keyword path: {Array} matched item path returns: {ReactNode} result content | \nFunction | \nrendering by pattern of a / b / c | \n
resultAutoWidth | \nwhether the search result list is equal to the selector | \nBoolean | \ntrue | \n
notFoundContent | \ncontent without data | \nReactNode | \n'Not Found' | \n
loadData | \nasynchronous data loading function signatures: Function(data: Object) => void params: data: {Object} data of the clicked item | \nFunction | \n- | \n
header | \ncustom dropdown header | \nReactNode | \n- | \n
footer | \ncustom dropdown footer | \nReactNode | \n- | \n
defaultVisible | \nwhether dropdown is default visible | \nBoolean | \nfalse | \n
visible | \nwhether dropdown is current visible | \nBoolean | \n- | \n
onVisibleChange | \ncallback triggered when open or close dropdown signatures: Function(visible: Boolean, type: String) => void params: visible: {Boolean} whether is visible type: {String} trigger type | \nFunction | \n() => {} | \n
popupStyle | \nstyle of dropdown | \nObject | \n- | \n
popupClassName | \nclassName of dropdown | \nString | \n- | \n
popupContainer | \ncontainer of dropdown | \nString/Function | \n- | \n
popupProps | \nproperties of Popup | \nObject | \n{} | \n
followTrigger | \nfollow Trigger or not | \nBoolean | \n- | \n
const dataSource = [{\n value: '2974',\n label: '西安',\n children: [\n { value: '2975', label: '西安市', disabled: true },\n { value: '2976', label: '高陵县', checkboxDisabled: true },\n { value: '2977', label: '蓝田县' },\n { value: '2978', label: '户县' },\n { value: '2979', label: '周至县' },\n { value: '4208', label: '灞桥区' },\n { value: '4209', label: '长安区' },\n { value: '4210', label: '莲湖区' },\n { value: '4211', label: '临潼区' },\n { value: '4212', label: '未央区' },\n { value: '4213', label: '新城区' },\n { value: '4214', label: '阎良区' },\n { value: '4215', label: '雁塔区' },\n { value: '4388', label: '碑林区' },\n { value: '610127', label: '其它区' }\n ]\n}];
The custom attribute of item in the array is also transparently passed to the data parameter of the onChange function.
\n\n按键 | \n说明 | \n
---|---|
Up Arrow | \nGet the previous item focus of the current item of same level | \n
Down Arrow | \nGet the next item focus of the current item of same level | \n
Left Arrow | \nEnter the child element of the current item and get the first child element as the focus | \n
Right Arrow | \nReturns the parent of the current item and gets the focus | \n
Enter | \nOpen the directory or select current item | \n
Esc | \nClose the directory | \n
SPACE | \nSelect current item | \n
级联选择由选择器和级联组成。把级联组件以弹层的方式隐藏,多用于表单场景。
\n参数 | \n说明 | \n类型 | \n默认值 | \n
---|---|---|---|
size | \n选择框大小 可选值: 'small', 'medium', 'large' | \nEnum | \n'medium' | \n
placeholder | \n选择框占位符 | \nString | \n- | \n
disabled | \n是否禁用 | \nBoolean | \nfalse | \n
hasArrow | \n是否有下拉箭头 | \nBoolean | \ntrue | \n
hasBorder | \n是否有边框 | \nBoolean | \ntrue | \n
hasClear | \n是否有清除按钮 | \nBoolean | \nfalse | \n
label | \n自定义内联 label | \nReactNode | \n- | \n
readOnly | \n是否只读,只读模式下可以展开弹层但不能选 | \nBoolean | \n- | \n
dataSource | \n数据源,结构可参考下方说明 | \nArray<Object> | \n[] | \n
defaultValue | \n(非受控)默认值 | \nString/Array<String> | \nnull | \n
value | \n(受控)当前值 | \nString/Array<String> | \n- | \n
onChange | \n选中值改变时触发的回调函数 签名: Function(value: String/Array, data: Object/Array, extra: Object) => void 参数: value: {String/Array} 选中的值,单选时返回单个值,多选时返回数组 data: {Object/Array} 选中的数据,包括 value 和 label,单选时返回单个值,多选时返回数组,父子节点选中关联时,同时选中,只返回父节点 extra: {Object} 额外参数 extra.selectedPath: {Array} 单选时选中的数据的路径 extra.checked: {Boolean} 多选时当前的操作是选中还是取消选中 extra.currentData: {Object} 多选时当前操作的数据 extra.checkedData: {Array} 多选时所有被选中的数据 extra.indeterminateData: {Array} 多选时半选的数据 | \nFunction | \n- | \n
defaultExpandedValue | \n默认展开值,如果不设置,组件内部会根据 defaultValue/value 进行自动设置 | \nArray<String> | \n- | \n
expandTriggerType | \n展开触发的方式 可选值: 'click', 'hover' | \nEnum | \n'click' | \n
useVirtual | \n是否开启虚拟滚动 | \nBoolean | \nfalse | \n
multiple | \n是否多选 | \nBoolean | \nfalse | \n
changeOnSelect | \n是否选中即发生改变, 该属性仅在单选模式下有效 | \nBoolean | \nfalse | \n
canOnlyCheckLeaf | \n是否只能勾选叶子项的checkbox,该属性仅在多选模式下有效 | \nBoolean | \nfalse | \n
checkStrictly | \n父子节点是否选中不关联 | \nBoolean | \nfalse | \n
listStyle | \n每列列表样式对象 | \nObject | \n- | \n
listClassName | \n每列列表类名 | \nString | \n- | \n
displayRender | \n选择框单选时展示结果的自定义渲染函数 签名: Function(label: Array) => ReactNode 参数: label: {Array} 选中路径的文本数组 返回值: {ReactNode} 渲染在选择框中的内容 | \nFunction | \n单选时:labelPath => labelPath.join(' / ');多选时:labelPath => labelPath[labelPath.length - 1] | \n
itemRender | \n渲染 item 内容的方法 签名: Function(item: Object) => ReactNode 参数: item: {Object} 渲染节点的item 返回值: {ReactNode} item node | \nFunction | \n- | \n
showSearch | \n是否显示搜索框 | \nBoolean | \nfalse | \n
filter | \n自定义搜索函数 签名: Function(searchValue: String, path: Array) => Boolean 参数: searchValue: {String} 搜索的关键字 path: {Array} 节点路径 返回值: {Boolean} 是否匹配 | \nFunction | \n根据路径所有节点的文本值模糊匹配 | \n
resultRender | \n搜索结果自定义渲染函数 签名: Function(searchValue: String, path: Array) => ReactNode 参数: searchValue: {String} 搜索的关键字 path: {Array} 匹配到的节点路径 返回值: {ReactNode} 渲染的内容 | \nFunction | \n按照节点文本 a / b / c 的模式渲染 | \n
resultAutoWidth | \n搜索结果列表是否和选择框等宽 | \nBoolean | \ntrue | \n
notFoundContent | \n无数据时显示内容 | \nReactNode | \n'Not Found' | \n
loadData | \n异步加载数据函数 签名: Function(data: Object) => void 参数: data: {Object} 当前点击异步加载的数据 | \nFunction | \n- | \n
header | \n自定义下拉框头部 | \nReactNode | \n- | \n
footer | \n自定义下拉框底部 | \nReactNode | \n- | \n
defaultVisible | \n初始下拉框是否显示 | \nBoolean | \nfalse | \n
visible | \n当前下拉框是否显示 | \nBoolean | \n- | \n
onVisibleChange | \n下拉框显示或关闭时触发事件的回调函数 签名: Function(visible: Boolean, type: String) => void 参数: visible: {Boolean} 是否显示 type: {String} 触发显示关闭的操作类型, fromTrigger 表示由trigger的点击触发; docClick 表示由document的点击触发 | \nFunction | \n() => {} | \n
popupStyle | \n下拉框自定义样式对象 | \nObject | \n- | \n
popupClassName | \n下拉框样式自定义类名 | \nString | \n- | \n
popupContainer | \n下拉框挂载的容器节点 | \nString/Function | \n- | \n
popupProps | \n透传到 Popup 的属性对象 | \nObject | \n{} | \n
followTrigger | \n是否跟随滚动 | \nBoolean | \n- | \n
const dataSource = [{\n value: '2974',\n label: '西安',\n children: [\n { value: '2975', label: '西安市', disabled: true },\n { value: '2976', label: '高陵县', checkboxDisabled: true },\n { value: '2977', label: '蓝田县' },\n { value: '2978', label: '户县' },\n { value: '2979', label: '周至县' },\n { value: '4208', label: '灞桥区' },\n { value: '4209', label: '长安区' },\n { value: '4210', label: '莲湖区' },\n { value: '4211', label: '临潼区' },\n { value: '4212', label: '未央区' },\n { value: '4213', label: '新城区' },\n { value: '4214', label: '阎良区' },\n { value: '4215', label: '雁塔区' },\n { value: '4388', label: '碑林区' },\n { value: '610127', label: '其它区' }\n ]\n}];
数组中 Item 的自定义属性也会被透传到 onChange 函数的 data 参数中。
\n\n按键 | \n说明 | \n
---|---|
Up Arrow | \n获取同级当前项前一项焦点 | \n
Down Arrow | \n获取同级当前项后一项焦点 | \n
Left Arrow | \n进入当前项的子元素,并获取第一个子元素为焦点 | \n
Right Arrow | \n返回当前项的父元素并获取焦点 | \n
Enter | \n打开目录或选择当前项 | \n
Esc | \n关闭目录 | \n
SPACE | \n选择当前项 | \n
Demo the basic single select usage.
\n","order":"0"},"codes":{"jsx":"import { Cascader } from '@alifd/next';\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n label: '',\n data: []\n };\n\n this.handleChange = this.handleChange.bind(this);\n }\n\n componentDidMount() {\n fetch('https://os.alipayobjects.com/rmsportal/ODDwqcDFTLAguOvWEolX.json')\n .then(response => response.json())\n .then(data => {\n data[1].disabled = true;\n this.setState({ data });\n })\n .catch(e => console.log(e));\n }\n\n handleChange(value, data, extra) {\n console.log(value, data, extra);\n\n this.setState({\n label: extra.selectedPath.map(d => d.label).join(' / ')\n });\n }\n\n render() {\n return (\nimport { Cascader } from '@alifd/next';\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n label: '',\n data: []\n };\n\n this.handleChange = this.handleChange.bind(this);\n }\n\n componentDidMount() {\n fetch('https://os.alipayobjects.com/rmsportal/ODDwqcDFTLAguOvWEolX.json')\n .then(response => response.json())\n .then(data => {\n data[1].disabled = true;\n this.setState({ data });\n })\n .catch(e => console.log(e));\n }\n\n handleChange(value, data, extra) {\n console.log(value, data, extra);\n\n this.setState({\n label: extra.selectedPath.map(d => d.label).join(' / ')\n });\n }\n\n render() {\n return (\n <div>\n <div className=\"cascader-value\">Select: {this.state.label}</div>\n <Cascader dataSource={this.state.data} onChange={this.handleChange} />\n </div>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
.cascader-value {\n margin-bottom: 10px;\n font-size: 14px;\n color: #666;\n}
展示基本的单选用法。
\n","order":"0"},"codes":{"jsx":"import { Cascader } from '@alifd/next';\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n label: '',\n data: []\n };\n\n this.handleChange = this.handleChange.bind(this);\n }\n\n componentDidMount() {\n fetch('https://os.alipayobjects.com/rmsportal/ODDwqcDFTLAguOvWEolX.json')\n .then(response => response.json())\n .then(data => {\n data[1].disabled = true;\n this.setState({ data });\n })\n .catch(e => console.log(e));\n }\n\n handleChange(value, data, extra) {\n console.log(value, data, extra);\n\n this.setState({\n label: extra.selectedPath.map(d => d.label).join(' / ')\n });\n }\n\n render() {\n return (\nimport { Cascader } from '@alifd/next';\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n label: '',\n data: []\n };\n\n this.handleChange = this.handleChange.bind(this);\n }\n\n componentDidMount() {\n fetch('https://os.alipayobjects.com/rmsportal/ODDwqcDFTLAguOvWEolX.json')\n .then(response => response.json())\n .then(data => {\n data[1].disabled = true;\n this.setState({ data });\n })\n .catch(e => console.log(e));\n }\n\n handleChange(value, data, extra) {\n console.log(value, data, extra);\n\n this.setState({\n label: extra.selectedPath.map(d => d.label).join(' / ')\n });\n }\n\n render() {\n return (\n <div>\n <div className=\"cascader-value\">Select: {this.state.label}</div>\n <Cascader dataSource={this.state.data} onChange={this.handleChange} />\n </div>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
.cascader-value {\n margin-bottom: 10px;\n font-size: 14px;\n color: #666;\n}
You can customize the component width and height with listStyle
and listClassName
.
import { Cascader } from '@alifd/next';\n\nconst dataSource = [{\n value: '2973',\n label: '陕西',\n children: [{\n value: '2974',\n label: '西安',\n children: [\n { value: '2975', label: '西安市' },\n { value: '2976', label: '高陵县' }\n ]\n }, {\n value: '2980',\n label: '铜川',\n children: [\n { value: '2981', label: '铜川市' },\n { value: '2982', label: '宜君县' }\n ]\n }]\n}, {\n value: '3371',\n label: '新疆',\n children: [{\n value: '3430',\n label: '巴音郭楞蒙古自治州',\n children: [\n { value: '3431', label: '库尔勒市' },\n { value: '3432', label: '和静县' }\n ]\n }]\n}];\n\nReactDOM.render(<Cascader defaultValue=\"3439\" defaultExpandedValue={['3371', '3430']} listStyle={{ width: '200px', height: '256px' }} dataSource={dataSource} />, mountNode);
可以通过listStyle
,listClassName
来定制组件宽高。
import { Cascader } from '@alifd/next';\n\nconst dataSource = [{\n value: '2973',\n label: '陕西',\n children: [{\n value: '2974',\n label: '西安',\n children: [\n { value: '2975', label: '西安市' },\n { value: '2976', label: '高陵县' }\n ]\n }, {\n value: '2980',\n label: '铜川',\n children: [\n { value: '2981', label: '铜川市' },\n { value: '2982', label: '宜君县' }\n ]\n }]\n}, {\n value: '3371',\n label: '新疆',\n children: [{\n value: '3430',\n label: '巴音郭楞蒙古自治州',\n children: [\n { value: '3431', label: '库尔勒市' },\n { value: '3432', label: '和静县' }\n ]\n }]\n}];\n\nReactDOM.render(<Cascader defaultValue=\"3439\" defaultExpandedValue={['3371', '3430']} listStyle={{ width: '200px', height: '256px' }} dataSource={dataSource} />, mountNode);
Demon loading data asynchronously.
\n","order":"6"},"codes":{"jsx":"import { Cascader } from '@alifd/next';\n\nconst dataSource = [{\n value: '2973',\n label: '陕西'\n}];\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n dataSource\n };\n\n this.onLoadData = this.onLoadData.bind(this);\n }\n\n onLoadData(data) {\n console.log(data);\n\n return new Promise(resolve => {\n setTimeout(() => {\n this.setState({\n dataSource: [{\n value: '2973',\n label: '陕西',\n children: [{\n value: '2974',\n label: '西安',\n children: [\n { value: '2975', label: '西安市', isLeaf: true },\n { value: '2976', label: '高陵县', isLeaf: true }\n ]\n }, {\n value: '2980',\n label: '铜川',\n children: [\n { value: '2981', label: '铜川市', isLeaf: true },\n { value: '2982', label: '宜君县', isLeaf: true }\n ]\n }]\n }]\n }, resolve);\n }, 500);\n });\n }\n\n render() {\n returnimport { Cascader } from '@alifd/next';\n\nconst dataSource = [{\n value: '2973',\n label: '陕西'\n}];\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n dataSource\n };\n\n this.onLoadData = this.onLoadData.bind(this);\n }\n\n onLoadData(data) {\n console.log(data);\n\n return new Promise(resolve => {\n setTimeout(() => {\n this.setState({\n dataSource: [{\n value: '2973',\n label: '陕西',\n children: [{\n value: '2974',\n label: '西安',\n children: [\n { value: '2975', label: '西安市', isLeaf: true },\n { value: '2976', label: '高陵县', isLeaf: true }\n ]\n }, {\n value: '2980',\n label: '铜川',\n children: [\n { value: '2981', label: '铜川市', isLeaf: true },\n { value: '2982', label: '宜君县', isLeaf: true }\n ]\n }]\n }]\n }, resolve);\n }, 500);\n });\n }\n\n render() {\n return <Cascader canOnlySelectLeaf dataSource={this.state.dataSource} loadData={this.onLoadData} />;\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
.cascader-value {\n margin-bottom: 10px;\n font-size: 14px;\n color: #666;\n}
展示动态获取数据的用法。
\n","order":"6"},"codes":{"jsx":"import { Cascader } from '@alifd/next';\n\nconst dataSource = [{\n value: '2973',\n label: '陕西'\n}];\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n dataSource\n };\n\n this.onLoadData = this.onLoadData.bind(this);\n }\n\n onLoadData(data) {\n console.log(data);\n\n return new Promise(resolve => {\n setTimeout(() => {\n this.setState({\n dataSource: [{\n value: '2973',\n label: '陕西',\n children: [{\n value: '2974',\n label: '西安',\n children: [\n { value: '2975', label: '西安市', isLeaf: true },\n { value: '2976', label: '高陵县', isLeaf: true }\n ]\n }, {\n value: '2980',\n label: '铜川',\n children: [\n { value: '2981', label: '铜川市', isLeaf: true },\n { value: '2982', label: '宜君县', isLeaf: true }\n ]\n }]\n }]\n }, resolve);\n }, 500);\n });\n }\n\n render() {\n returnimport { Cascader } from '@alifd/next';\n\nconst dataSource = [{\n value: '2973',\n label: '陕西'\n}];\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n dataSource\n };\n\n this.onLoadData = this.onLoadData.bind(this);\n }\n\n onLoadData(data) {\n console.log(data);\n\n return new Promise(resolve => {\n setTimeout(() => {\n this.setState({\n dataSource: [{\n value: '2973',\n label: '陕西',\n children: [{\n value: '2974',\n label: '西安',\n children: [\n { value: '2975', label: '西安市', isLeaf: true },\n { value: '2976', label: '高陵县', isLeaf: true }\n ]\n }, {\n value: '2980',\n label: '铜川',\n children: [\n { value: '2981', label: '铜川市', isLeaf: true },\n { value: '2982', label: '宜君县', isLeaf: true }\n ]\n }]\n }]\n }, resolve);\n }, 500);\n });\n }\n\n render() {\n return <Cascader canOnlySelectLeaf dataSource={this.state.dataSource} loadData={this.onLoadData} />;\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
.cascader-value {\n margin-bottom: 10px;\n font-size: 14px;\n color: #666;\n}
You can set expand trigger type by setting expandTriggerType
, support click
and hover
, the default is click
.
import { Radio, Cascader } from '@alifd/next';\n\nconst RadioGroup = Radio.Group;\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n triggerType: 'click',\n data: []\n };\n\n this.handleChange = this.handleChange.bind(this);\n this.handleTriggerTypeChange = this.handleTriggerTypeChange.bind(this);\n }\n\n componentDidMount() {\n fetch('https://os.alipayobjects.com/rmsportal/ODDwqcDFTLAguOvWEolX.json')\n .then(response => response.json())\n .then(data => this.setState({ data }))\n .catch(e => console.log(e));\n }\n\n handleChange(value, data, extra) {\n console.log(value, data, extra);\n }\n\n handleTriggerTypeChange(triggerType) {\n this.setState({\n triggerType\n });\n }\n\n render() {\n return (\n <div>\n <div className=\"trigger-check\">\n Expand trigger type:\n <RadioGroup dataSource={['click', 'hover']} value={this.state.triggerType} onChange={this.handleTriggerTypeChange} />\n </div>\n\n <Cascader expandTriggerType={this.state.triggerType} dataSource={this.state.data} onChange={this.handleChange} />\n </div>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
.trigger-check {\n margin-bottom: 10px;\n font-size: 14px;\n color: #666;\n}\n\n.trigger-check .next-radio-group {\n margin-left: 10px;\n}
展示可通过expandTriggerType
来设置不同的展开触发行为,支持click
和hover
,默认值为click
。
import { Radio, Cascader } from '@alifd/next';\n\nconst RadioGroup = Radio.Group;\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n triggerType: 'click',\n data: []\n };\n\n this.handleChange = this.handleChange.bind(this);\n this.handleTriggerTypeChange = this.handleTriggerTypeChange.bind(this);\n }\n\n componentDidMount() {\n fetch('https://os.alipayobjects.com/rmsportal/ODDwqcDFTLAguOvWEolX.json')\n .then(response => response.json())\n .then(data => this.setState({ data }))\n .catch(e => console.log(e));\n }\n\n handleChange(value, data, extra) {\n console.log(value, data, extra);\n }\n\n handleTriggerTypeChange(triggerType) {\n this.setState({\n triggerType\n });\n }\n\n render() {\n return (\n <div>\n <div className=\"trigger-check\">\n Expand trigger type:\n <RadioGroup dataSource={['click', 'hover']} value={this.state.triggerType} onChange={this.handleTriggerTypeChange} />\n </div>\n\n <Cascader expandTriggerType={this.state.triggerType} dataSource={this.state.data} onChange={this.handleChange} />\n </div>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
.trigger-check {\n margin-bottom: 10px;\n font-size: 14px;\n color: #666;\n}\n\n.trigger-check .next-radio-group {\n margin-left: 10px;\n}
Demo whether parent and child nodes checked is related.
\n","order":"4"},"codes":{"jsx":"import { Checkbox, Cascader } from '@alifd/next';\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n value: [],\n data: [],\n checkStrictly: false\n };\n\n this.handleCheck = this.handleCheck.bind(this);\n this.handleChange = this.handleChange.bind(this);\n }\n\n componentDidMount() {\n fetch('https://os.alipayobjects.com/rmsportal/ODDwqcDFTLAguOvWEolX.json')\n .then(response => response.json())\n .then(data => this.setState({ data, value: ['2975'] }))\n .catch(e => console.log(e));\n }\n\n handleCheck() {\n this.setState({\n checkStrictly: !this.state.checkStrictly,\n value: []\n });\n }\n\n handleChange(value, data, extra) {\n console.log(value, data, extra);\n\n this.setState({\n value\n });\n }\n\n render() {\n return (\nimport { Checkbox, Cascader } from '@alifd/next';\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n value: [],\n data: [],\n checkStrictly: false\n };\n\n this.handleCheck = this.handleCheck.bind(this);\n this.handleChange = this.handleChange.bind(this);\n }\n\n componentDidMount() {\n fetch('https://os.alipayobjects.com/rmsportal/ODDwqcDFTLAguOvWEolX.json')\n .then(response => response.json())\n .then(data => this.setState({ data, value: ['2975'] }))\n .catch(e => console.log(e));\n }\n\n handleCheck() {\n this.setState({\n checkStrictly: !this.state.checkStrictly,\n value: []\n });\n }\n\n handleChange(value, data, extra) {\n console.log(value, data, extra);\n\n this.setState({\n value\n });\n }\n\n render() {\n return (\n <div className=\"control-multiple-demo\">\n <label className=\"strictly-check\">\n <Checkbox value={this.state.checkStrictly} onChange={this.handleCheck} />\n <span className=\"strictly-text\">Enable checkStrictly</span>\n </label>\n <Cascader multiple checkStrictly={this.state.checkStrictly} value={this.state.value} dataSource={this.state.data} onChange={this.handleChange} />\n </div>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
.control-multiple-demo .strictly-check {\n display: block;\n margin-bottom: 10px;\n}\n\n.control-multiple-demo .strictly-text {\n display: inline-block;\n margin-left: 10px;\n vertical-align: middle;\n color: #666;\n font-size: 14px;\n}
展示受控多选以及是否开启严格受控父子节点选中不再关联的用法。
\n","order":"4"},"codes":{"jsx":"import { Checkbox, Cascader } from '@alifd/next';\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n value: [],\n data: [],\n checkStrictly: false\n };\n\n this.handleCheck = this.handleCheck.bind(this);\n this.handleChange = this.handleChange.bind(this);\n }\n\n componentDidMount() {\n fetch('https://os.alipayobjects.com/rmsportal/ODDwqcDFTLAguOvWEolX.json')\n .then(response => response.json())\n .then(data => this.setState({ data, value: ['2975'] }))\n .catch(e => console.log(e));\n }\n\n handleCheck() {\n this.setState({\n checkStrictly: !this.state.checkStrictly,\n value: []\n });\n }\n\n handleChange(value, data, extra) {\n console.log(value, data, extra);\n\n this.setState({\n value\n });\n }\n\n render() {\n return (\nimport { Checkbox, Cascader } from '@alifd/next';\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n value: [],\n data: [],\n checkStrictly: false\n };\n\n this.handleCheck = this.handleCheck.bind(this);\n this.handleChange = this.handleChange.bind(this);\n }\n\n componentDidMount() {\n fetch('https://os.alipayobjects.com/rmsportal/ODDwqcDFTLAguOvWEolX.json')\n .then(response => response.json())\n .then(data => this.setState({ data, value: ['2975'] }))\n .catch(e => console.log(e));\n }\n\n handleCheck() {\n this.setState({\n checkStrictly: !this.state.checkStrictly,\n value: []\n });\n }\n\n handleChange(value, data, extra) {\n console.log(value, data, extra);\n\n this.setState({\n value\n });\n }\n\n render() {\n return (\n <div className=\"control-multiple-demo\">\n <label className=\"strictly-check\">\n <Checkbox value={this.state.checkStrictly} onChange={this.handleCheck} />\n <span className=\"strictly-text\">Enable checkStrictly</span>\n </label>\n <Cascader multiple checkStrictly={this.state.checkStrictly} value={this.state.value} dataSource={this.state.data} onChange={this.handleChange} />\n </div>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
.control-multiple-demo .strictly-check {\n display: block;\n margin-bottom: 10px;\n}\n\n.control-multiple-demo .strictly-text {\n display: inline-block;\n margin-left: 10px;\n vertical-align: middle;\n color: #666;\n font-size: 14px;\n}
Demo the basic multiple select usage.
\n","order":"2"},"codes":{"jsx":"import { Cascader } from '@alifd/next';\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n label: '',\n data: []\n };\n\n this.handleChange = this.handleChange.bind(this);\n }\n\n componentDidMount() {\n fetch('https://os.alipayobjects.com/rmsportal/ODDwqcDFTLAguOvWEolX.json')\n .then(response => response.json())\n .then(data => {\n data[1].disabled = true;\n data[2].checkboxDisabled = true;\n this.setState({ data });\n })\n .catch(e => console.log(e));\n }\n\n handleChange(value, data, extra) {\n console.log(value, data, extra);\n\n this.setState({\n label: data.map(d => d.label).join(', ')\n });\n }\n\n render() {\n return (\nimport { Cascader } from '@alifd/next';\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n label: '',\n data: []\n };\n\n this.handleChange = this.handleChange.bind(this);\n }\n\n componentDidMount() {\n fetch('https://os.alipayobjects.com/rmsportal/ODDwqcDFTLAguOvWEolX.json')\n .then(response => response.json())\n .then(data => {\n data[1].disabled = true;\n data[2].checkboxDisabled = true;\n this.setState({ data });\n })\n .catch(e => console.log(e));\n }\n\n handleChange(value, data, extra) {\n console.log(value, data, extra);\n\n this.setState({\n label: data.map(d => d.label).join(', ')\n });\n }\n\n render() {\n return (\n <div>\n <div className=\"cascader-value\">Select: {this.state.label}</div>\n <Cascader multiple dataSource={this.state.data} onChange={this.handleChange} />\n </div>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
.cascader-value {\n width: 500px;\n margin-bottom: 10px;\n font-size: 14px;\n color: #666;\n}
展示基本的多选用法。
\n","order":"2"},"codes":{"jsx":"import { Cascader } from '@alifd/next';\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n label: '',\n data: []\n };\n\n this.handleChange = this.handleChange.bind(this);\n }\n\n componentDidMount() {\n fetch('https://os.alipayobjects.com/rmsportal/ODDwqcDFTLAguOvWEolX.json')\n .then(response => response.json())\n .then(data => {\n data[1].disabled = true;\n data[2].checkboxDisabled = true;\n this.setState({ data });\n })\n .catch(e => console.log(e));\n }\n\n handleChange(value, data, extra) {\n console.log(value, data, extra);\n\n this.setState({\n label: data.map(d => d.label).join(', ')\n });\n }\n\n render() {\n return (\nimport { Cascader } from '@alifd/next';\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n label: '',\n data: []\n };\n\n this.handleChange = this.handleChange.bind(this);\n }\n\n componentDidMount() {\n fetch('https://os.alipayobjects.com/rmsportal/ODDwqcDFTLAguOvWEolX.json')\n .then(response => response.json())\n .then(data => {\n data[1].disabled = true;\n data[2].checkboxDisabled = true;\n this.setState({ data });\n })\n .catch(e => console.log(e));\n }\n\n handleChange(value, data, extra) {\n console.log(value, data, extra);\n\n this.setState({\n label: data.map(d => d.label).join(', ')\n });\n }\n\n render() {\n return (\n <div>\n <div className=\"cascader-value\">Select: {this.state.label}</div>\n <Cascader multiple dataSource={this.state.data} onChange={this.handleChange} />\n </div>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
.cascader-value {\n width: 500px;\n margin-bottom: 10px;\n font-size: 14px;\n color: #666;\n}
Demo the controlled single select and whether it can only select leaf items.
\n","order":"3"},"codes":{"jsx":"import { Checkbox, Cascader } from '@alifd/next';\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n value: null,\n canOnlySelectLeaf: false,\n data: []\n };\n\n this.handleCheck = this.handleCheck.bind(this);\n this.handleChange = this.handleChange.bind(this);\n }\n\n componentDidMount() {\n fetch('https://os.alipayobjects.com/rmsportal/ODDwqcDFTLAguOvWEolX.json')\n .then(response => response.json())\n .then(data => this.setState({ data, value: '2975' }))\n .catch(e => console.log(e));\n }\n\n handleCheck() {\n this.setState({\n canOnlySelectLeaf: !this.state.canOnlySelectLeaf,\n value: null\n });\n }\n\n handleChange(value, data, extra) {\n console.log(value, data, extra);\n\n this.setState({\n value\n });\n }\n\n render() {\n return (\nimport { Checkbox, Cascader } from '@alifd/next';\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n value: null,\n canOnlySelectLeaf: false,\n data: []\n };\n\n this.handleCheck = this.handleCheck.bind(this);\n this.handleChange = this.handleChange.bind(this);\n }\n\n componentDidMount() {\n fetch('https://os.alipayobjects.com/rmsportal/ODDwqcDFTLAguOvWEolX.json')\n .then(response => response.json())\n .then(data => this.setState({ data, value: '2975' }))\n .catch(e => console.log(e));\n }\n\n handleCheck() {\n this.setState({\n canOnlySelectLeaf: !this.state.canOnlySelectLeaf,\n value: null\n });\n }\n\n handleChange(value, data, extra) {\n console.log(value, data, extra);\n\n this.setState({\n value\n });\n }\n\n render() {\n return (\n <div className=\"control-single-demo\">\n <label className=\"leaf-check\">\n <Checkbox value={this.state.canOnlySelectLeaf} onChange={this.handleCheck} />\n <span className=\"leaf-text\">Enable canOnlySelectLeaf</span>\n </label>\n <Cascader canOnlySelectLeaf={this.state.canOnlySelectLeaf} value={this.state.value} dataSource={this.state.data} onChange={this.handleChange} />\n </div>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
.control-single-demo .leaf-check {\n display: block;\n margin-bottom: 10px;\n}\n\n.control-single-demo .leaf-text {\n display: inline-block;\n margin-left: 10px;\n vertical-align: middle;\n color: #666;\n font-size: 14px;\n}
展示受控单选以及是否只能选择叶子项的用法。
\n","order":"3"},"codes":{"jsx":"import { Checkbox, Cascader } from '@alifd/next';\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n value: null,\n canOnlySelectLeaf: false,\n data: []\n };\n\n this.handleCheck = this.handleCheck.bind(this);\n this.handleChange = this.handleChange.bind(this);\n }\n\n componentDidMount() {\n fetch('https://os.alipayobjects.com/rmsportal/ODDwqcDFTLAguOvWEolX.json')\n .then(response => response.json())\n .then(data => this.setState({ data, value: '2975' }))\n .catch(e => console.log(e));\n }\n\n handleCheck() {\n this.setState({\n canOnlySelectLeaf: !this.state.canOnlySelectLeaf,\n value: null\n });\n }\n\n handleChange(value, data, extra) {\n console.log(value, data, extra);\n\n this.setState({\n value\n });\n }\n\n render() {\n return (\nimport { Checkbox, Cascader } from '@alifd/next';\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n value: null,\n canOnlySelectLeaf: false,\n data: []\n };\n\n this.handleCheck = this.handleCheck.bind(this);\n this.handleChange = this.handleChange.bind(this);\n }\n\n componentDidMount() {\n fetch('https://os.alipayobjects.com/rmsportal/ODDwqcDFTLAguOvWEolX.json')\n .then(response => response.json())\n .then(data => this.setState({ data, value: '2975' }))\n .catch(e => console.log(e));\n }\n\n handleCheck() {\n this.setState({\n canOnlySelectLeaf: !this.state.canOnlySelectLeaf,\n value: null\n });\n }\n\n handleChange(value, data, extra) {\n console.log(value, data, extra);\n\n this.setState({\n value\n });\n }\n\n render() {\n return (\n <div className=\"control-single-demo\">\n <label className=\"leaf-check\">\n <Checkbox value={this.state.canOnlySelectLeaf} onChange={this.handleCheck} />\n <span className=\"leaf-text\">Enable canOnlySelectLeaf</span>\n </label>\n <Cascader canOnlySelectLeaf={this.state.canOnlySelectLeaf} value={this.state.value} dataSource={this.state.data} onChange={this.handleChange} />\n </div>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
.control-single-demo .leaf-check {\n display: block;\n margin-bottom: 10px;\n}\n\n.control-single-demo .leaf-text {\n display: inline-block;\n margin-left: 10px;\n vertical-align: middle;\n color: #666;\n font-size: 14px;\n}
Demon loading data asynchronously.
\n","order":"7"},"codes":{"jsx":"import { Cascader } from '@alifd/next';\n\nconst dataSource = [{\n value: '2974',\n label: '西安'\n}, {\n value: '2980',\n label: '铜川'\n}];\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n dataSource\n };\n\n this.onLoadData = this.onLoadData.bind(this);\n }\n\n onLoadData(data, source) {\n console.log(data, source);\n\n return new Promise(resolve => {\n source.children = source.value === '2974' ? [\n { value: '2975', label: '西安市', isLeaf: true },\n { value: '2976', label: '高陵县', isLeaf: true }\n ] : [\n { value: '2981', label: '铜川市', isLeaf: true },\n { value: '2982', label: '宜君县', isLeaf: true }\n ];\n setTimeout(() => {\n this.setState({\n dataSource: this.state.dataSource\n }, resolve);\n }, 500);\n });\n }\n\n render() {\n returnimport { Cascader } from '@alifd/next';\n\nconst dataSource = [{\n value: '2974',\n label: '西安'\n}, {\n value: '2980',\n label: '铜川'\n}];\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n dataSource\n };\n\n this.onLoadData = this.onLoadData.bind(this);\n }\n\n onLoadData(data, source) {\n console.log(data, source);\n\n return new Promise(resolve => {\n source.children = source.value === '2974' ? [\n { value: '2975', label: '西安市', isLeaf: true },\n { value: '2976', label: '高陵县', isLeaf: true }\n ] : [\n { value: '2981', label: '铜川市', isLeaf: true },\n { value: '2982', label: '宜君县', isLeaf: true }\n ];\n setTimeout(() => {\n this.setState({\n dataSource: this.state.dataSource\n }, resolve);\n }, 500);\n });\n }\n\n render() {\n return <Cascader canOnlySelectLeaf dataSource={this.state.dataSource} loadData={this.onLoadData} />;\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
.cascader-value {\n margin-bottom: 10px;\n font-size: 14px;\n color: #666;\n}
展示动态获取数据的用法。
\n","order":"7"},"codes":{"jsx":"import { Cascader } from '@alifd/next';\n\nconst dataSource = [{\n value: '2974',\n label: '西安'\n}, {\n value: '2980',\n label: '铜川'\n}];\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n dataSource\n };\n\n this.onLoadData = this.onLoadData.bind(this);\n }\n\n onLoadData(data, source) {\n console.log(data, source);\n\n return new Promise(resolve => {\n source.children = source.value === '2974' ? [\n { value: '2975', label: '西安市', isLeaf: true },\n { value: '2976', label: '高陵县', isLeaf: true }\n ] : [\n { value: '2981', label: '铜川市', isLeaf: true },\n { value: '2982', label: '宜君县', isLeaf: true }\n ];\n setTimeout(() => {\n this.setState({\n dataSource: this.state.dataSource\n }, resolve);\n }, 500);\n });\n }\n\n render() {\n returnimport { Cascader } from '@alifd/next';\n\nconst dataSource = [{\n value: '2974',\n label: '西安'\n}, {\n value: '2980',\n label: '铜川'\n}];\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n dataSource\n };\n\n this.onLoadData = this.onLoadData.bind(this);\n }\n\n onLoadData(data, source) {\n console.log(data, source);\n\n return new Promise(resolve => {\n source.children = source.value === '2974' ? [\n { value: '2975', label: '西安市', isLeaf: true },\n { value: '2976', label: '高陵县', isLeaf: true }\n ] : [\n { value: '2981', label: '铜川市', isLeaf: true },\n { value: '2982', label: '宜君县', isLeaf: true }\n ];\n setTimeout(() => {\n this.setState({\n dataSource: this.state.dataSource\n }, resolve);\n }, 500);\n });\n }\n\n render() {\n return <Cascader canOnlySelectLeaf dataSource={this.state.dataSource} loadData={this.onLoadData} />;\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
.cascader-value {\n margin-bottom: 10px;\n font-size: 14px;\n color: #666;\n}
Param | \nDescription | \nType | \nDefault Value | \n
---|---|---|---|
dataSource | \ndata source, structure can refer to the following document | \nArray<Object> | \n[] | \n
defaultValue | \n(under uncontrol) default value | \nString/Array<String> | \nnull | \n
value | \n(under control) current value | \nString/Array<String> | \n- | \n
onChange | \ncallback triggered when value changes signatures: Function(value: String/Array, data: Object/Array, extra: Object) => void params: value: {String/Array} selected value, a single value is returned when single select, and an array is returned when multiple select data: {Object/Array} selected data, including value, label, returns a single value when single select, returns an array when multiple select, parent and child nodes are selected at the same time, only the parent node is returned extra: {Object} extra param extra.selectedPath: {Array} path of the selected data when single selecte extra.checked: {Boolean} whether is checked when multiple select extra.currentData: {Object} current operation data when multiple select extra.checkedData: {Array} all checked data when multiple select extra.indeterminateData: {Array} indeterminate data when multile select | \nFunction | \n- | \n
defaultExpandedValue | \n(under uncontrol) default expanded value, if not set, the component will be automatically set according to defaultValue/value | \nArray<String> | \n- | \n
expandedValue | \n(under control) current expanded value | \nArray<String> | \n- | \n
expandTriggerType | \nexpand trigger type options: 'click', 'hover' | \nEnum | \n'click' | \n
onExpand | \ncallback triggered when expand or collapse signatures: Function(expandedValue: Array) => void params: expandedValue: {Array} an array of list expanded values | \nFunction | \n- | \n
multiple | \nwhether is multiple select | \nBoolean | \nfalse | \n
canOnlySelectLeaf | \nwhether only leaf nodes can be selected when single select | \nBoolean | \nfalse | \n
canOnlyCheckLeaf | \nwhether only leaf nodes can be checked when multiple select | \nBoolean | \nfalse | \n
checkStrictly | \nwhether selection of parent and child nodes are related | \nBoolean | \nfalse | \n
listStyle | \nstyle of list | \nObject | \n- | \n
listClassName | \nclass name of list | \nString | \n- | \n
itemRender | \nrender function of item signatures: Function(data: Object) => ReactNode params: data: {Object} data returns: {ReactNode} content of item | \nFunction | \nitem => item.label | \n
loadData | \nasynchronous data loading function signatures: Function(data: Object) => void params: data: {Object} clicked item | \nFunction | \n- | \n
const dataSource = [{\n value: '2974',\n label: 'A',\n children: [\n { value: '2975', label: 'B', disabled: true },\n { value: '2976', label: 'C', checkboxDisabled: true },\n { value: '2977', label: 'D' },\n { value: '2978', label: 'E' },\n { value: '2979', label: 'F' },\n { value: '4208', label: 'G' },\n { value: '4209', label: 'H' },\n { value: '4210', label: 'I' },\n { value: '4211', label: 'J' },\n { value: '4212', label: 'K' },\n { value: '4213', label: 'L' },\n { value: '4214', label: 'M' },\n { value: '4215', label: 'N' },\n { value: '4388', label: 'O' },\n { value: '610127', label: 'P' }\n ]\n}];
The custom attribute of item in the array is also transparently passed to the data parameter of the onChange function.
\n\n按键 | \n说明 | \n
---|---|
Left Arrow | \nGet the previous item focus of the current item of same level | \n
Right Arrow | \nGet the next item focus of the current item of same level | \n
Tab | \nEnter the child element of the current item and get the first child element as the focus | \n
Esc | \nReturns the parent of the current item and gets the focus | \n
SPACE | \nSelect current item | \n
参数 | \n说明 | \n类型 | \n默认值 | \n
---|---|---|---|
dataSource | \n数据源,结构可参考下方说明 | \nArray<Object> | \n[] | \n
defaultValue | \n(非受控)默认值 | \nString/Array<String> | \nnull | \n
value | \n(受控)当前值 | \nString/Array<String> | \n- | \n
onChange | \n选中值改变时触发的回调函数 签名: Function(value: String/Array, data: Object/Array, extra: Object) => void 参数: value: {String/Array} 选中的值,单选时返回单个值,多选时返回数组 data: {Object/Array} 选中的数据,包括 value 和 label,单选时返回单个值,多选时返回数组,父子节点选中关联时,同时选中,只返回父节点 extra: {Object} 额外参数 extra.selectedPath: {Array} 单选时选中的数据的路径 extra.checked: {Boolean} 多选时当前的操作是选中还是取消选中 extra.currentData: {Object} 多选时当前操作的数据 extra.checkedData: {Array} 多选时所有被选中的数据 extra.indeterminateData: {Array} 多选时半选的数据 | \nFunction | \n- | \n
defaultExpandedValue | \n(非受控)默认展开值,如果不设置,组件内部会根据 defaultValue/value 进行自动设置 | \nArray<String> | \n- | \n
expandedValue | \n(受控)当前展开值 | \nArray<String> | \n- | \n
expandTriggerType | \n展开触发的方式 可选值: 'click', 'hover' | \nEnum | \n'click' | \n
onExpand | \n展开时触发的回调函数 签名: Function(expandedValue: Array) => void 参数: expandedValue: {Array} 各列展开值的数组 | \nFunction | \n- | \n
useVirtual | \n是否开启虚拟滚动 | \nBoolean | \nfalse | \n
multiple | \n是否多选 | \nBoolean | \nfalse | \n
canOnlySelectLeaf | \n单选时是否只能选中叶子节点 | \nBoolean | \nfalse | \n
canOnlyCheckLeaf | \n多选时是否只能选中叶子节点 | \nBoolean | \nfalse | \n
checkStrictly | \n父子节点是否选中不关联 | \nBoolean | \nfalse | \n
listStyle | \n每列列表样式对象 | \nObject | \n- | \n
listClassName | \n每列列表类名 | \nString | \n- | \n
itemRender | \n每列列表项渲染函数 签名: Function(data: Object) => ReactNode 参数: data: {Object} 数据 返回值: {ReactNode} 列表项内容 | \nFunction | \nitem => item.label | \n
loadData | \n异步加载数据函数 签名: Function(data: Object, source: Object) => void 参数: data: {Object} 当前点击异步加载的数据 source: {Object} 当前点击数据,source是原始对象 | \nFunction | \n- | \n
const dataSource = [{\n value: '2974',\n label: '西安',\n children: [\n { value: '2975', label: '西安市', disabled: true },\n { value: '2976', label: '高陵县', checkboxDisabled: true },\n { value: '2977', label: '蓝田县' },\n { value: '2978', label: '户县' },\n { value: '2979', label: '周至县' },\n { value: '4208', label: '灞桥区' },\n { value: '4209', label: '长安区' },\n { value: '4210', label: '莲湖区' },\n { value: '4211', label: '临潼区' },\n { value: '4212', label: '未央区' },\n { value: '4213', label: '新城区' },\n { value: '4214', label: '阎良区' },\n { value: '4215', label: '雁塔区' },\n { value: '4388', label: '碑林区' },\n { value: '610127', label: '其它区' }\n ]\n}];
数组中 Item 的自定义属性也会被透传到 onChange 函数的 data 参数中。
\n\n按键 | \n说明 | \n
---|---|
Left Arrow | \n获取同级当前项前一项焦点 | \n
Right Arrow | \n获取同级当前项后一项焦点 | \n
Tab | \n进入当前项的子元素,并获取第一个子元素为焦点 | \n
Esc | \n返回当前项的父元素并获取焦点 | \n
SPACE | \n选择当前项 | \n
Describe the Checkbox
component with aria-label
.Please refer to ARIA and KeyBoard
for keyboard operation.
\nimport { Checkbox } from '@alifd/next';\n\nconst CheckboxGroup = () => (\n <div>\n <h4>Programming language:</h4>\n <Checkbox.Group aria-label=\"Please select a programming language\"> \n <Checkbox value=\"python\">python</Checkbox>\n <Checkbox value=\"java\">java</Checkbox>\n <Checkbox value=\"angular\">angular</Checkbox>\n <Checkbox value=\"c\">c</Checkbox>\n <Checkbox value=\"other\">other</Checkbox>\n </Checkbox.Group>\n </div>\n);\n\nReactDOM.render(<CheckboxGroup />, mountNode);\n
通过aria-label
对Checkbox
组件进行描述。关于键盘操作请参考ARIA and KeyBoard
。
\nimport { Checkbox } from '@alifd/next';\n\nconst CheckboxGroup = () => (\n <div>\n <h4>Programming language:</h4>\n <Checkbox.Group aria-label=\"Please select a programming language\"> \n <Checkbox value=\"python\">python</Checkbox>\n <Checkbox value=\"java\">java</Checkbox>\n <Checkbox value=\"angular\">angular</Checkbox>\n <Checkbox value=\"c\">c</Checkbox>\n <Checkbox value=\"other\">other</Checkbox>\n </Checkbox.Group>\n </div>\n);\n\nReactDOM.render(<CheckboxGroup />, mountNode);\n
import { Checkbox } from '@alifd/next';\n\nReactDOM.render(\n <div>\n <h6>Different status without label:</h6>\n <Checkbox >Unchecked</Checkbox>\n <Checkbox defaultChecked >DefaultChecked</Checkbox>\n <Checkbox defaultIndeterminate >Indeterminate</Checkbox>\n <Checkbox disabled >Disabled</Checkbox>;\n <Checkbox disabled checked >Checked-Disabled</Checkbox>\n <Checkbox checked >Checked</Checkbox>\n <h6>Using with label</h6>\n <Checkbox>Banana</Checkbox> \n <Checkbox id=\"apple\" /><label htmlFor=\"apple\" className=\"next-checkbox-label\">Apple</label> \n <label>\n <Checkbox id=\"pear\" />\n <span className=\"next-checkbox-label\">Pear</span>\n </label> \n <Checkbox label=\"Banana\" />\n </div>, mountNode);
使用 Checkbox
渲染的基本组件。
import { Checkbox } from '@alifd/next';\n\nReactDOM.render(\n <div>\n <h6>Different status without label:</h6>\n <Checkbox >Unchecked</Checkbox>\n <Checkbox defaultChecked >DefaultChecked</Checkbox>\n <Checkbox defaultIndeterminate >Indeterminate</Checkbox>\n <Checkbox disabled >Disabled</Checkbox>;\n <Checkbox disabled checked >Checked-Disabled</Checkbox>\n <Checkbox checked >Checked</Checkbox>\n <h6>Using with label</h6>\n <Checkbox>Banana</Checkbox> \n <Checkbox id=\"apple\" /><label htmlFor=\"apple\" className=\"next-checkbox-label\">Apple</label> \n <label>\n <Checkbox id=\"pear\" />\n <span className=\"next-checkbox-label\">Pear</span>\n </label> \n <Checkbox label=\"Banana\" />\n </div>, mountNode);
import { Checkbox } from '@alifd/next';\n\nconst { Group: CheckboxGroup } = Checkbox;\nconst list = [\n {\n value: 'apple',\n label: 'Apple'\n }, {\n value: 'pear',\n label: 'Pear'\n }, {\n value: 'orange',\n label: 'Orange'\n }\n];\n\nclass ControlApp extends React.Component {\n\n constructor(props) {\n super(props);\n\n this.state = {\n value: ['orange']\n };\n\n this.onChange = this.onChange.bind(this);\n }\n\n onChange(selectedItems) {\n console.log('onChange callback', selectedItems);\n this.setState({\n value: selectedItems\n });\n }\n\n render() {\n return (\n <div style={{padding: '20px'}}>\n <CheckboxGroup value={this.state.value} dataSource={list} onChange={this.onChange} />\n </div>\n );\n }\n\n}\n\nReactDOM.render(<ControlApp />, mountNode);
使用 CheckboxGroup
渲染的组,通过设置 value
属性可以让组件变成受限组件。
import { Checkbox } from '@alifd/next';\n\nconst { Group: CheckboxGroup } = Checkbox;\nconst list = [\n {\n value: 'apple',\n label: 'Apple'\n }, {\n value: 'pear',\n label: 'Pear'\n }, {\n value: 'orange',\n label: 'Orange'\n }\n];\n\nclass ControlApp extends React.Component {\n\n constructor(props) {\n super(props);\n\n this.state = {\n value: ['orange']\n };\n\n this.onChange = this.onChange.bind(this);\n }\n\n onChange(selectedItems) {\n console.log('onChange callback', selectedItems);\n this.setState({\n value: selectedItems\n });\n }\n\n render() {\n return (\n <div style={{padding: '20px'}}>\n <CheckboxGroup value={this.state.value} dataSource={list} onChange={this.onChange} />\n </div>\n );\n }\n\n}\n\nReactDOM.render(<ControlApp />, mountNode);
Grouping <Checkbox>
with <Checkbox.Group>
.
\n
\n
\n
\n
import { Checkbox } from '@alifd/next';\n\nconst CheckboxGroup = () => (\n <div>\n <h4>Horizonal direction</h4>\n <p>\n <Checkbox.Group itemDirection=\"hoz\">\n <Checkbox value=\"react\">React</Checkbox>\n <Checkbox value=\"vue\">Vue</Checkbox>\n <Checkbox value=\"angular\">Angular</Checkbox>\n </Checkbox.Group>\n </p>\n <h4>Vertical direction</h4>\n <p>\n <Checkbox.Group itemDirection=\"ver\">\n <Checkbox value=\"react\">React</Checkbox>\n <Checkbox value=\"vue\">Vue</Checkbox>\n <Checkbox value=\"angular\">Angular</Checkbox>\n </Checkbox.Group>\n </p>\n </div>\n);\n\nReactDOM.render(<CheckboxGroup />, mountNode);
使用 <Checkbox.Group>
渲染 <Checkbox>
分组。
\n
\n
\n
\n
import { Checkbox } from '@alifd/next';\n\nconst CheckboxGroup = () => (\n <div>\n <h4>Horizonal direction</h4>\n <p>\n <Checkbox.Group itemDirection=\"hoz\">\n <Checkbox value=\"react\">React</Checkbox>\n <Checkbox value=\"vue\">Vue</Checkbox>\n <Checkbox value=\"angular\">Angular</Checkbox>\n </Checkbox.Group>\n </p>\n <h4>Vertical direction</h4>\n <p>\n <Checkbox.Group itemDirection=\"ver\">\n <Checkbox value=\"react\">React</Checkbox>\n <Checkbox value=\"vue\">Vue</Checkbox>\n <Checkbox value=\"angular\">Angular</Checkbox>\n </Checkbox.Group>\n </p>\n </div>\n);\n\nReactDOM.render(<CheckboxGroup />, mountNode);
import { Checkbox, Button } from '@alifd/next';\n\nclass IndeterminateApp extends React.Component {\n\n constructor(props) {\n super(props);\n\n this.state = {\n checked: false,\n indeterminate: true,\n disabled: false\n };\n }\n\n render() {\n return (\n <div>\n <Checkbox\n checked={this.state.checked}\n indeterminate={this.state.indeterminate}\n disabled={this.state.disabled}\n onChange={\n (checked) => {\n this.setState({checked: checked, indeterminate: false});\n }\n }\n />\n <br />\n <br />\n <Button\n type=\"primary\"\n onClick={\n () => {\n this.setState({checked: true, indeterminate: false});\n }\n }>checked = true</Button>\n <br />\n <br />\n <Button\n type=\"primary\"\n onClick={\n () => {\n this.setState({checked: false});\n }\n }\n >checked = false</Button>\n <br />\n <br />\n <Button\n type=\"primary\"\n onClick={\n () => {\n this.setState({checked: false, indeterminate: true});\n }\n }\n >indeterminate = true</Button>\n <br />\n <br />\n <Button\n type=\"primary\"\n onClick={\n () => {\n this.setState({indeterminate: false});\n }\n }\n >indeterminate = false</Button>\n <br />\n <br />\n <Button\n type=\"primary\"\n onClick={\n () => {\n this.setState({disabled: !this.state.disabled});\n }\n }\n >toggle disabled</Button>\n </div>\n );\n }\n}\n\nReactDOM.render(<IndeterminateApp />, mountNode);
通过使用 indeterminate
来渲染中间状态的组件。
import { Checkbox, Button } from '@alifd/next';\n\nclass IndeterminateApp extends React.Component {\n\n constructor(props) {\n super(props);\n\n this.state = {\n checked: false,\n indeterminate: true,\n disabled: false\n };\n }\n\n render() {\n return (\n <div>\n <Checkbox\n checked={this.state.checked}\n indeterminate={this.state.indeterminate}\n disabled={this.state.disabled}\n onChange={\n (checked) => {\n this.setState({checked: checked, indeterminate: false});\n }\n }\n />\n <br />\n <br />\n <Button\n type=\"primary\"\n onClick={\n () => {\n this.setState({checked: true, indeterminate: false});\n }\n }>checked = true</Button>\n <br />\n <br />\n <Button\n type=\"primary\"\n onClick={\n () => {\n this.setState({checked: false});\n }\n }\n >checked = false</Button>\n <br />\n <br />\n <Button\n type=\"primary\"\n onClick={\n () => {\n this.setState({checked: false, indeterminate: true});\n }\n }\n >indeterminate = true</Button>\n <br />\n <br />\n <Button\n type=\"primary\"\n onClick={\n () => {\n this.setState({indeterminate: false});\n }\n }\n >indeterminate = false</Button>\n <br />\n <br />\n <Button\n type=\"primary\"\n onClick={\n () => {\n this.setState({disabled: !this.state.disabled});\n }\n }\n >toggle disabled</Button>\n </div>\n );\n }\n}\n\nReactDOM.render(<IndeterminateApp />, mountNode);
import { Checkbox } from '@alifd/next';\n\nconst { Group: CheckboxGroup } = Checkbox;\n\nclass NestApp extends React.Component {\n\n constructor(props) {\n super(props);\n\n this.state = {\n value: ['orange']\n };\n\n this.onChange = this.onChange.bind(this);\n }\n\n onChange(selectedItems) {\n this.setState({\n value: selectedItems\n });\n }\n\n render() {\n return (\n <div>\n <CheckboxGroup value={this.state.value} onChange={this.onChange}>\n <Checkbox id=\"apple\" value=\"apple\" disabled>Apple</Checkbox>\n <Checkbox id=\"watermelon\" value=\"watermelon\">Watermelon</Checkbox>\n <Checkbox id=\"orange\" value=\"orange\">Orange</Checkbox>\n </CheckboxGroup>\n </div>\n );\n }\n}\n\nReactDOM.render(<NestApp />, mountNode);
使用 CheckboxGroup
,通过直接嵌套 Checkbox
组件来渲染的组。
import { Checkbox } from '@alifd/next';\n\nconst { Group: CheckboxGroup } = Checkbox;\n\nclass NestApp extends React.Component {\n\n constructor(props) {\n super(props);\n\n this.state = {\n value: ['orange']\n };\n\n this.onChange = this.onChange.bind(this);\n }\n\n onChange(selectedItems) {\n this.setState({\n value: selectedItems\n });\n }\n\n render() {\n return (\n <div>\n <CheckboxGroup value={this.state.value} onChange={this.onChange}>\n <Checkbox id=\"apple\" value=\"apple\" disabled>Apple</Checkbox>\n <Checkbox id=\"watermelon\" value=\"watermelon\">Watermelon</Checkbox>\n <Checkbox id=\"orange\" value=\"orange\">Orange</Checkbox>\n </CheckboxGroup>\n </div>\n );\n }\n}\n\nReactDOM.render(<NestApp />, mountNode);
import { Checkbox } from '@alifd/next';\n\nconst { Group: CheckboxGroup } = Checkbox;\nconst list = [\n {\n value: 'apple',\n label: 'Apple',\n disabled: false\n }, {\n value: 'pear',\n label: 'Pear'\n }, {\n value: 'orange',\n label: 'Orange',\n disabled: true\n }\n];\n\nclass UnControlApp extends React.Component {\n\n constructor(props) {\n super(props);\n\n this.onChange = this.onChange.bind(this);\n }\n\n onChange(selectedItems) {\n console.log('onChange callback', selectedItems);\n }\n\n render() {\n return (\n <div style={{padding: '20px'}}>\n <CheckboxGroup defaultValue={['apple']} dataSource={list} onChange={this.onChange} />\n </div>\n );\n }\n\n}\n\nReactDOM.render(<UnControlApp />, mountNode);
使用 CheckboxGroup
渲染的组,通过设置 defaultValue
属性可以让组件变成非受限组件。
import { Checkbox } from '@alifd/next';\n\nconst { Group: CheckboxGroup } = Checkbox;\nconst list = [\n {\n value: 'apple',\n label: 'Apple',\n disabled: false\n }, {\n value: 'pear',\n label: 'Pear'\n }, {\n value: 'orange',\n label: 'Orange',\n disabled: true\n }\n];\n\nclass UnControlApp extends React.Component {\n\n constructor(props) {\n super(props);\n\n this.onChange = this.onChange.bind(this);\n }\n\n onChange(selectedItems) {\n console.log('onChange callback', selectedItems);\n }\n\n render() {\n return (\n <div style={{padding: '20px'}}>\n <CheckboxGroup defaultValue={['apple']} dataSource={list} onChange={this.onChange} />\n </div>\n );\n }\n\n}\n\nReactDOM.render(<UnControlApp />, mountNode);
Checkbox
\nCheckbox is used to verify which options you want selected from a group. If you have only a single option, do not use the checkbox, use the on/off switch.
\nParam | \nDescription | \nType | \nDefault Value | \n
---|---|---|---|
id | \ncheckbox id, mounted on input | \nString | \n- | \n
checked | \nSet the status to be checked | \nBoolean | \n- | \n
defaultChecked | \nSet the default status to be checked | \nBoolean | \nfalse | \n
disabled | \nSet the status to be disabled | \nBoolean | \n- | \n
label | \nSet the label by property | \nString | \n- | \n
indeterminate | \nThe intermediate state of the Checkbox will only affect the style of the Checkbox and does not affect its checked property. | \nBoolean | \n- | \n
defaultIndeterminate | \nSet the default status to intermediate, it will only affect the style of the Checkbox and does not affect its checked property. | \nBoolean | \nfalse | \n
onChange | \nCallback function triggered when the state changes signatures: Function(checked: Boolean, e: Event) => void params: checked: {Boolean} The checked value of the underlying checkbox input _e_: {Event} Dom event object | \nFunction | \nfunc.noop | \n
onMouseEnter | \nCallback function triggered when the mouse pointer enters the element. signatures: Function(e: Event) => void params: _e_: {Event} Dom event object | \nFunction | \nfunc.noop | \n
onMouseLeave | \nCallback function triggered when the mouse pointer leaves the element. signatures: Function(e: Event) => void params: _e_: {Event} Dom event object | \nFunction | \nfunc.noop | \n
params | \ndesc | \ntype | \ndefault | \n
---|---|---|---|
disabled | \nSet the status of all checkbox in group to be checked | \nBoolean | \n- | \n
dataSource | \nOptional list, data item can be String or Object, for example ['apple', 'pear', 'orange'] or [{value: 'apple', label: 'Apple',}, {value: 'pear', label: 'Pear'}, {value: 'orange', label: 'Orange'}] | \nArray<any> | \n[] | \n
value | \nThe values of selected optional list | \nArray/String/Number | \n- | \n
defaultValue | \nThe values of default selected optional list | \nArray/String/Number | \n- | \n
children | \nTo set nested checkbox by children components | \nArray<ReactElement> | \n- | \n
onChange | \nCallback function triggered when the selected value changes signatures: Function(value: Array, e: Event) => void params: value: {Array} values of selected optional list _e_: {Event} Dom event object | \nFunction | \n() => { } | \n
itemDirection | \nThe direction of item's aligning - hoz: horizontal (default) - ver: vertical Allowed values: 'hoz', 'ver' | \nEnum | \n'hoz' | \n
KeyBoard | \nDescripiton | \n
---|---|
SPACE | \nSelect or cancel the current item | \n
多选框
\n复选框允许用户从一个数据集中选择多个选项。如果在一个列表中有多个选项,你可以通过使用复选框而不是开/关切换来节省空间。如果你有一个单选项,不要用复选框,使用开/关切换。
\n参数 | \n说明 | \n类型 | \n默认值 | \n
---|---|---|---|
id | \ncheckbox id, 挂载在input上 | \nString | \n- | \n
checked | \n选中状态 | \nBoolean | \n- | \n
defaultChecked | \n默认选中状态 | \nBoolean | \nfalse | \n
disabled | \n禁用 | \nBoolean | \n- | \n
label | \n通过属性配置label, | \nReactNode | \n- | \n
indeterminate | \nCheckbox 的中间状态,只会影响到 Checkbox 的样式,并不影响其 checked 属性 | \nBoolean | \n- | \n
defaultIndeterminate | \nCheckbox 的默认中间态,只会影响到 Checkbox 的样式,并不影响其 checked 属性 | \nBoolean | \nfalse | \n
onChange | \n状态变化时触发的事件 签名: Function(checked: Boolean, e: Event) => void 参数: checked: {Boolean} 是否选中 _e_: {Event} Dom 事件对象 | \nFunction | \nfunc.noop | \n
onMouseEnter | \n鼠标进入enter事件 签名: Function(e: Event) => void 参数: _e_: {Event} Dom 事件对象 | \nFunction | \nfunc.noop | \n
onMouseLeave | \n鼠标离开Leave事件 签名: Function(e: Event) => void 参数: _e_: {Event} Dom 事件对象 | \nFunction | \nfunc.noop | \n
value | \ncheckbox 的value | \nString/Number | \n- | \n
name | \nname | \nString | \n- | \n
参数 | \n说明 | \n类型 | \n默认值 | \n
---|---|---|---|
disabled | \n整体禁用 | \nBoolean | \n- | \n
dataSource | \n可选项列表, 数据项可为 String 或者 Object, 如 ['apple', 'pear', 'orange'] 或者 [{value: 'apple', label: '苹果',}, {value: 'pear', label: '梨'}, {value: 'orange', label: '橙子'}] | \nArray<String>/Array<Object> | \n[] | \n
value | \n被选中的值列表 | \nArray/String/Number | \n- | \n
defaultValue | \n默认被选中的值列表 | \nArray/String/Number | \n- | \n
children | \n通过子元素方式设置内部 checkbox | \nArray<ReactElement> | \n- | \n
onChange | \n选中值改变时的事件 签名: Function(value: Array, e: Event) => void 参数: value: {Array} 选中项列表 _e_: {Event} Dom 事件对象 | \nFunction | \n() => {} | \n
itemDirection | \n子项目的排列方式 - hoz: 水平排列 (default) - ver: 垂直排列 可选值: 'hoz', 'ver' | \nEnum | \n'hoz' | \n
按键 | \n说明 | \n
---|---|
SPACE | \n选择或取消当前项 | \n
To Support accessibility, you shoud assign an id prop to Collapse and it will generate id for Panels. or you can assign an id prop to Panel to overwrite generated id.
\n","order":"5"},"codes":{"jsx":"import { Collapse } from '@alifd/next';\n\nconst Panel = Collapse.Panel;\n\nReactDOM.render(import { Collapse } from '@alifd/next';\n\nconst Panel = Collapse.Panel;\n\nReactDOM.render(<Collapse id=\"collapse-accessibility\">\n <Panel\n id=\"panel-accessibility\"\n title=\"There is a long title, you can set the multiTitle to multi line display, the associated configuration properties and a single height is not the same, the specific configuration platform configuration can be configured.\">\n <ul>\n <li>Promotions are marketing campaigns ran by Marketplace</li>\n <li>Participate to sale your products during that promotion and make a profit</li>\n </ul>\n </Panel>\n <Panel title=\"What are Promotion Products?\">\n <ul>\n <li>Promotion Products is a service that helps you to promote products you list on Marketplace during a\n certain time range\n </li>\n <li>You can choose which products should be available for the promotion</li>\n <li>Not all Products of you will be available, because Promotions will only attract certain Product areas\n </li>\n </ul>\n </Panel>\n\n</Collapse>, mountNode);
组件内置了部分支持无障碍, 但是额外需要开发者手动事情才能完整支持无障碍: 给Collapse传入一个id, 组件会根据Collapse的id自动给每一个Panel生成Id。如果你想指定Panel的Id也可以, 给某个Panel传入Id属性,就会覆盖根据CollapseId生成的Id。
\n","order":"5"},"codes":{"jsx":"import { Collapse } from '@alifd/next';\n\nconst Panel = Collapse.Panel;\n\nReactDOM.render(import { Collapse } from '@alifd/next';\n\nconst Panel = Collapse.Panel;\n\nReactDOM.render(<Collapse id=\"collapse-accessibility\">\n <Panel\n id=\"panel-accessibility\"\n title=\"There is a long title, you can set the multiTitle to multi line display, the associated configuration properties and a single height is not the same, the specific configuration platform configuration can be configured.\">\n <ul>\n <li>Promotions are marketing campaigns ran by Marketplace</li>\n <li>Participate to sale your products during that promotion and make a profit</li>\n </ul>\n </Panel>\n <Panel title=\"What are Promotion Products?\">\n <ul>\n <li>Promotion Products is a service that helps you to promote products you list on Marketplace during a\n certain time range\n </li>\n <li>You can choose which products should be available for the promotion</li>\n <li>Not all Products of you will be available, because Promotions will only attract certain Product areas\n </li>\n </ul>\n </Panel>\n\n</Collapse>, mountNode);
Accordion mode, you can only open at most one panel.
\n","order":"2"},"codes":{"jsx":"import { Collapse } from '@alifd/next';\n\nconst Panel = Collapse.Panel;\n\nReactDOM.render(import { Collapse } from '@alifd/next';\n\nconst Panel = Collapse.Panel;\n\nReactDOM.render(<Collapse accordion>\n <Panel\n title=\"There is a long title, you can set the multiTitle to multi line display, the associated configuration properties and a single height is not the same, the specific configuration platform configuration can be configured.\">\n <ul>\n <li>Promotions are marketing campaigns ran by Marketplace</li>\n <li>Participate to sale your products during that promotion and make a profit</li>\n </ul>\n </Panel>\n <Panel title=\"What are Promotion Products?\">\n <ul>\n <li>Promotion Products is a service that helps you to promote products you list on Marketplace during a\n certain time range\n </li>\n <li>You can choose which products should be available for the promotion</li>\n <li>Not all Products of you will be available, because Promotions will only attract certain Product areas\n </li>\n </ul>\n </Panel>\n <Panel title=\"Why can i not submit a higher price?\">\n <ul>\n <li>The Promotion requires a certain price to make sure that our customers are attracted</li>\n </ul>\n </Panel>\n <Panel title=\"What is Promo Stock?\">\n Promo Stock is the criteria needed to be followed to be able to join Promotion. With setting particular Promo\n Stock value you commit to have this amount of stock available while Promotion is active.\n </Panel>\n</Collapse>, mountNode);
手风琴单例模式,每次只打开一个Panel。
\n","order":"2"},"codes":{"jsx":"import { Collapse } from '@alifd/next';\n\nconst Panel = Collapse.Panel;\n\nReactDOM.render(import { Collapse } from '@alifd/next';\n\nconst Panel = Collapse.Panel;\n\nReactDOM.render(<Collapse accordion>\n <Panel\n title=\"There is a long title, you can set the multiTitle to multi line display, the associated configuration properties and a single height is not the same, the specific configuration platform configuration can be configured.\">\n <ul>\n <li>Promotions are marketing campaigns ran by Marketplace</li>\n <li>Participate to sale your products during that promotion and make a profit</li>\n </ul>\n </Panel>\n <Panel title=\"What are Promotion Products?\">\n <ul>\n <li>Promotion Products is a service that helps you to promote products you list on Marketplace during a\n certain time range\n </li>\n <li>You can choose which products should be available for the promotion</li>\n <li>Not all Products of you will be available, because Promotions will only attract certain Product areas\n </li>\n </ul>\n </Panel>\n <Panel title=\"Why can i not submit a higher price?\">\n <ul>\n <li>The Promotion requires a certain price to make sure that our customers are attracted</li>\n </ul>\n </Panel>\n <Panel title=\"What is Promo Stock?\">\n Promo Stock is the criteria needed to be followed to be able to join Promotion. With setting particular Promo\n Stock value you commit to have this amount of stock available while Promotion is active.\n </Panel>\n</Collapse>, mountNode);
import { Collapse, Radio } from '@alifd/next';\n\nconst Panel = Collapse.Panel;\nconst RadioGroup = Radio.Group;\n\nconst RTL = 'rtl';\nconst LTR = 'ltr';\n\nclass App extends React.Component {\n constructor(props) {\n super(props);\n this.state = {\n rtl: false\n };\n this.handleDirectionChange = this.handleDirectionChange.bind(this);\n }\n\n handleDirectionChange(v) {\n this.setState({\n rtl: !this.state.rtl\n });\n }\n\n render() {\n return (<div>\n <RadioGroup dataSource={['ltr', 'rtl']} value={this.state.rtl ? 'rtl' : 'ltr'} onChange={this.handleDirectionChange} />\n <Collapse rtl={this.state.rtl}>\n <Panel title=\"simple tile\">\n <ul>\n <li>Promotions are marketing campaigns ran by Marketplace</li>\n <li>Participate to sale your products during that promotion and make a profit</li>\n </ul>\n </Panel>\n <Panel title=\"What are Promotion Products?\">\n <ul>\n <li>Promotion Products is a service that helps you to promote products you list on Marketplace during a certain time range</li>\n <li>You can choose which products should be available for the promotion</li>\n <li>Not all Products of you will be available, because Promotions will only attract certain Product areas</li>\n </ul>\n </Panel>\n <Panel title=\"Why can i not submit a higher price?\">\n <ul>\n <li>The Promotion requires a certain price to make sure that our customers are attracted</li>\n </ul>\n </Panel>\n <Panel title=\"What is Promo Stock?\">\n Promo Stock is the criteria needed to be followed to be able to join Promotion. With setting particular Promo Stock value you commit to have this amount of stock available while Promotion is active.\n </Panel>\n </Collapse>\n </div>);\n }\n}\n\nReactDOM.render(\n <App />,\n mountNode);
import { Collapse, Radio } from '@alifd/next';\n\nconst Panel = Collapse.Panel;\nconst RadioGroup = Radio.Group;\n\nconst RTL = 'rtl';\nconst LTR = 'ltr';\n\nclass App extends React.Component {\n constructor(props) {\n super(props);\n this.state = {\n rtl: false\n };\n this.handleDirectionChange = this.handleDirectionChange.bind(this);\n }\n\n handleDirectionChange(v) {\n this.setState({\n rtl: !this.state.rtl\n });\n }\n\n render() {\n return (<div>\n <RadioGroup dataSource={['ltr', 'rtl']} value={this.state.rtl ? 'rtl' : 'ltr'} onChange={this.handleDirectionChange} />\n <Collapse rtl={this.state.rtl}>\n <Panel title=\"simple tile\">\n <ul>\n <li>Promotions are marketing campaigns ran by Marketplace</li>\n <li>Participate to sale your products during that promotion and make a profit</li>\n </ul>\n </Panel>\n <Panel title=\"What are Promotion Products?\">\n <ul>\n <li>Promotion Products is a service that helps you to promote products you list on Marketplace during a certain time range</li>\n <li>You can choose which products should be available for the promotion</li>\n <li>Not all Products of you will be available, because Promotions will only attract certain Product areas</li>\n </ul>\n </Panel>\n <Panel title=\"Why can i not submit a higher price?\">\n <ul>\n <li>The Promotion requires a certain price to make sure that our customers are attracted</li>\n </ul>\n </Panel>\n <Panel title=\"What is Promo Stock?\">\n Promo Stock is the criteria needed to be followed to be able to join Promotion. With setting particular Promo Stock value you commit to have this amount of stock available while Promotion is active.\n </Panel>\n </Collapse>\n </div>);\n }\n}\n\nReactDOM.render(\n <App />,\n mountNode);
import { Collapse } from '@alifd/next';\n\nconst list = [\n {\n title: 'Well, hello there',\n content: 'Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.',\n disabled: true\n },\n {\n title: 'Gigantomaniac Monster Text, very long, much width, wow',\n content: 'Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.'\n },\n {\n title: 'Generic Title',\n content: 'Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.'\n },\n {\n title: 'Login Infomation',\n content: 'Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.'\n }\n];\n\nReactDOM.render(<Collapse dataSource={list}/>, mountNode);
import { Collapse } from '@alifd/next';\n\nconst list = [\n {\n title: 'Well, hello there',\n content: 'Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.',\n disabled: true\n },\n {\n title: 'Gigantomaniac Monster Text, very long, much width, wow',\n content: 'Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.'\n },\n {\n title: 'Generic Title',\n content: 'Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.'\n },\n {\n title: 'Login Infomation',\n content: 'Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.'\n }\n];\n\nReactDOM.render(<Collapse dataSource={list}/>, mountNode);
import { Collapse } from '@alifd/next';\n\nconst Panel = Collapse.Panel;\n\nReactDOM.render(\n <div>\n <Collapse disabled>\n <Panel title=\"disable collapse\">\n <ul>\n <li>Promotions are marketing campaigns ran by Marketplace</li>\n <li>Participate to sale your products during that promotion and make a profit</li>\n </ul>\n </Panel>\n <Panel title=\"disable collapse\">\n <ul>\n <li>Promotion Products is a service that helps you to promote products you list on Marketplace during a certain time range</li>\n <li>You can choose which products should be available for the promotion</li>\n <li>Not all Products of you will be available, because Promotions will only attract certain Product areas</li>\n </ul>\n </Panel>\n <Panel title=\"disable collapse\">\n <ul>\n <li>The Promotion requires a certain price to make sure that our customers are attracted</li>\n </ul>\n </Panel>\n <Panel title=\"disable collapse\">\n Promo Stock is the criteria needed to be followed to be able to join Promotion. With setting particular Promo Stock value you commit to have this amount of stock available while Promotion is active.\n </Panel>\n </Collapse>\n <br />\n <Collapse>\n <Panel title=\"simple title(disabled)\" disabled>\n <ul>\n <li>Promotions are marketing campaigns ran by Marketplace</li>\n <li>Participate to sale your products during that promotion and make a profit</li>\n </ul>\n </Panel>\n <Panel title=\"What are Promotion Products?(disabled)\" disabled>\n <ul>\n <li>Promotion Products is a service that helps you to promote products you list on Marketplace during a certain time range</li>\n <li>You can choose which products should be available for the promotion</li>\n <li>Not all Products of you will be available, because Promotions will only attract certain Product areas</li>\n </ul>\n </Panel>\n <Panel title=\"Why can i not submit a higher price?\">\n <ul>\n <li>The Promotion requires a certain price to make sure that our customers are attracted</li>\n </ul>\n </Panel>\n <Panel title=\"What is Promo Stock?\">\n Promo Stock is the criteria needed to be followed to be able to join Promotion. With setting particular Promo Stock value you commit to have this amount of stock available while Promotion is active.\n </Panel>\n </Collapse>\n </div>,\n mountNode);
import { Collapse } from '@alifd/next';\n\nconst Panel = Collapse.Panel;\n\nReactDOM.render(\n <div>\n <Collapse disabled>\n <Panel title=\"disable collapse\">\n <ul>\n <li>Promotions are marketing campaigns ran by Marketplace</li>\n <li>Participate to sale your products during that promotion and make a profit</li>\n </ul>\n </Panel>\n <Panel title=\"disable collapse\">\n <ul>\n <li>Promotion Products is a service that helps you to promote products you list on Marketplace during a certain time range</li>\n <li>You can choose which products should be available for the promotion</li>\n <li>Not all Products of you will be available, because Promotions will only attract certain Product areas</li>\n </ul>\n </Panel>\n <Panel title=\"disable collapse\">\n <ul>\n <li>The Promotion requires a certain price to make sure that our customers are attracted</li>\n </ul>\n </Panel>\n <Panel title=\"disable collapse\">\n Promo Stock is the criteria needed to be followed to be able to join Promotion. With setting particular Promo Stock value you commit to have this amount of stock available while Promotion is active.\n </Panel>\n </Collapse>\n <br />\n <Collapse>\n <Panel title=\"simple title(disabled)\" disabled>\n <ul>\n <li>Promotions are marketing campaigns ran by Marketplace</li>\n <li>Participate to sale your products during that promotion and make a profit</li>\n </ul>\n </Panel>\n <Panel title=\"What are Promotion Products?(disabled)\" disabled>\n <ul>\n <li>Promotion Products is a service that helps you to promote products you list on Marketplace during a certain time range</li>\n <li>You can choose which products should be available for the promotion</li>\n <li>Not all Products of you will be available, because Promotions will only attract certain Product areas</li>\n </ul>\n </Panel>\n <Panel title=\"Why can i not submit a higher price?\">\n <ul>\n <li>The Promotion requires a certain price to make sure that our customers are attracted</li>\n </ul>\n </Panel>\n <Panel title=\"What is Promo Stock?\">\n Promo Stock is the criteria needed to be followed to be able to join Promotion. With setting particular Promo Stock value you commit to have this amount of stock available while Promotion is active.\n </Panel>\n </Collapse>\n </div>,\n mountNode);
import { Collapse } from '@alifd/next';\n\nconst Panel = Collapse.Panel;\n\nclass Demo extends React.Component {\n constructor(props, context) {\n super(props, context);\n this.state = {\n expandedKeys: []\n };\n }\n\n onExpand(expandedKeys) {\n this.setState({\n expandedKeys\n });\n }\n\n onClick(key) {\n console.log('clicked', key);\n }\n render() {\n return (\n <Collapse onExpand={this.onExpand.bind(this)} expandedKeys={this.state.expandedKeys} >\n <Panel title=\"simple tile\" onClick={this.onClick}>\n <ul>\n <li>Promotions are marketing campaigns ran by Marketplace</li>\n <li>Participate to sale your products during that promotion and make a profit</li>\n </ul>\n </Panel>\n <Panel title=\"What are Promotion Products?\">\n <ul>\n <li>Promotion Products is a service that helps you to promote products you list on Marketplace during a certain time range</li>\n <li>You can choose which products should be available for the promotion</li>\n <li>Not all Products of you will be available, because Promotions will only attract certain Product areas</li>\n </ul>\n </Panel>\n <Panel title=\"Why can i not submit a higher price?\">\n <ul>\n <li>The Promotion requires a certain price to make sure that our customers are attracted</li>\n </ul>\n </Panel>\n <Panel title=\"What is Promo Stock?\">\n Promo Stock is the criteria needed to be followed to be able to join Promotion. With setting particular Promo Stock value you commit to have this amount of stock available while Promotion is active.\n </Panel>\n </Collapse>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
import { Collapse } from '@alifd/next';\n\nconst Panel = Collapse.Panel;\n\nclass Demo extends React.Component {\n constructor(props, context) {\n super(props, context);\n this.state = {\n expandedKeys: []\n };\n }\n\n onExpand(expandedKeys) {\n this.setState({\n expandedKeys\n });\n }\n\n onClick(key) {\n console.log('clicked', key);\n }\n render() {\n return (\n <Collapse onExpand={this.onExpand.bind(this)} expandedKeys={this.state.expandedKeys} >\n <Panel title=\"simple tile\" onClick={this.onClick}>\n <ul>\n <li>Promotions are marketing campaigns ran by Marketplace</li>\n <li>Participate to sale your products during that promotion and make a profit</li>\n </ul>\n </Panel>\n <Panel title=\"What are Promotion Products?\">\n <ul>\n <li>Promotion Products is a service that helps you to promote products you list on Marketplace during a certain time range</li>\n <li>You can choose which products should be available for the promotion</li>\n <li>Not all Products of you will be available, because Promotions will only attract certain Product areas</li>\n </ul>\n </Panel>\n <Panel title=\"Why can i not submit a higher price?\">\n <ul>\n <li>The Promotion requires a certain price to make sure that our customers are attracted</li>\n </ul>\n </Panel>\n <Panel title=\"What is Promo Stock?\">\n Promo Stock is the criteria needed to be followed to be able to join Promotion. With setting particular Promo Stock value you commit to have this amount of stock available while Promotion is active.\n </Panel>\n </Collapse>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
import { Collapse } from '@alifd/next';\n\nconst Panel = Collapse.Panel;\n\nReactDOM.render(\n <div>\n <Collapse>\n <Panel title=\"simple tile\">\n <Collapse>\n <Panel title=\"simple tile\">\n <ul>\n <li>Promotions are marketing campaigns ran by Marketplace</li>\n <li>Participate to sale your products during that promotion and make a profit</li>\n </ul>\n </Panel>\n <Panel title=\"What are Promotion Products?\">\n <ul>\n <li>Promotion Products is a service that helps you to promote products you list on Marketplace during a certain time range</li>\n <li>You can choose which products should be available for the promotion</li>\n <li>Not all Products of you will be available, because Promotions will only attract certain Product areas</li>\n </ul>\n </Panel>\n <Panel title=\"Why can i not submit a higher price?\">\n <ul>\n <li>The Promotion requires a certain price to make sure that our customers are attracted</li>\n </ul>\n </Panel>\n <Panel title=\"What is Promo Stock?\">\n Promo Stock is the criteria needed to be followed to be able to join Promotion. With setting particular Promo Stock value you commit to have this amount of stock available while Promotion is active.\n </Panel>\n </Collapse>\n </Panel>\n <Panel title=\"What are Promotion Products?\">\n <ul>\n <li>Promotion Products is a service that helps you to promote products you list on Marketplace during a certain time range</li>\n <li>You can choose which products should be available for the promotion</li>\n <li>Not all Products of you will be available, because Promotions will only attract certain Product areas</li>\n </ul>\n </Panel>\n\n </Collapse>\n </div>,\n mountNode);
import { Collapse } from '@alifd/next';\n\nconst Panel = Collapse.Panel;\n\nReactDOM.render(\n <div>\n <Collapse>\n <Panel title=\"simple tile\">\n <Collapse>\n <Panel title=\"simple tile\">\n <ul>\n <li>Promotions are marketing campaigns ran by Marketplace</li>\n <li>Participate to sale your products during that promotion and make a profit</li>\n </ul>\n </Panel>\n <Panel title=\"What are Promotion Products?\">\n <ul>\n <li>Promotion Products is a service that helps you to promote products you list on Marketplace during a certain time range</li>\n <li>You can choose which products should be available for the promotion</li>\n <li>Not all Products of you will be available, because Promotions will only attract certain Product areas</li>\n </ul>\n </Panel>\n <Panel title=\"Why can i not submit a higher price?\">\n <ul>\n <li>The Promotion requires a certain price to make sure that our customers are attracted</li>\n </ul>\n </Panel>\n <Panel title=\"What is Promo Stock?\">\n Promo Stock is the criteria needed to be followed to be able to join Promotion. With setting particular Promo Stock value you commit to have this amount of stock available while Promotion is active.\n </Panel>\n </Collapse>\n </Panel>\n <Panel title=\"What are Promotion Products?\">\n <ul>\n <li>Promotion Products is a service that helps you to promote products you list on Marketplace during a certain time range</li>\n <li>You can choose which products should be available for the promotion</li>\n <li>Not all Products of you will be available, because Promotions will only attract certain Product areas</li>\n </ul>\n </Panel>\n\n </Collapse>\n </div>,\n mountNode);
When some earas may toggle between collapse state and expand state.
\nParam | \nDescription | \nType | \nDefault Value | \n
---|---|---|---|
dataSource | \ndata model | \nArray | \n- | \n
defaultExpandedKeys | \ndefault expand panel keys | \nArray | \n- | \n
expandedKeys | \nexpand panel keys | \nArray | \n- | \n
onExpand | \ncallback when panel state changes signature: Function() => void | \nFunction | \nfunc.noop | \n
disabled | \ndisable all panel | \nBoolean | \n- | \n
accordion | \naccordion mode, you can only open at most one panel | \nBoolean | \nfalse | \n
Param | \nDescription | \nType | \nDefault Value | \n
---|---|---|---|
disabled | \ndisable this panel | \nBoolean | \n- | \n
title | \npanel title | \nReactNode | \n- | \n
KeyBoard | \nDescripiton | \n
---|---|
Tab | \nnavigate to the next collapse panel | \n
Space | \ntoggle expanded | \n
可以折叠/展开的内容区域。
\n参数 | \n说明 | \n类型 | \n默认值 | \n
---|---|---|---|
dataSource | \n使用数据模型构建 | \nArray | \n- | \n
defaultExpandedKeys | \n默认展开keys | \nArray | \n- | \n
expandedKeys | \n受控展开keys | \nArray | \n- | \n
onExpand | \n展开状态发升变化时候的回调 签名: Function() => void | \nFunction | \nfunc.noop | \n
disabled | \n所有禁用 | \nBoolean | \n- | \n
accordion | \n手风琴模式,一次只能打开一个 | \nBoolean | \nfalse | \n
参数 | \n说明 | \n类型 | \n默认值 | \n
---|---|---|---|
disabled | \n是否禁止用户操作 | \nBoolean | \n- | \n
title | \n标题 | \nReactNode | \n- | \n
按键 | \n说明 | \n
---|---|
Tab | \n切换到下一个collapse panel | \n
Space | \n切换collapse的折叠状态 | \n
The simplest usage, demo how ConfigProvider works.
\n","order":"1"},"codes":{"jsx":"import { ConfigProvider } from '@alifd/next';\nimport PropTypes from 'prop-types';\n\nconst { config } = ConfigProvider;\n\nclass Output extends React.Component {\n static propTypes = {\n prefix: PropTypes.string,\n locale: PropTypes.object,\n pure: PropTypes.bool\n };\n\n static defaultProps = {\n prefix: 'next-',\n locale: {\n hello: '你好'\n },\n pure: false\n };\n\n render() {\n const { prefix, locale, pure } = this.props;\n\n return (\nimport { ConfigProvider } from '@alifd/next';\nimport PropTypes from 'prop-types';\n\nconst { config } = ConfigProvider;\n\nclass Output extends React.Component {\n static propTypes = {\n prefix: PropTypes.string,\n locale: PropTypes.object,\n pure: PropTypes.bool\n };\n\n static defaultProps = {\n prefix: 'next-',\n locale: {\n hello: '你好'\n },\n pure: false\n };\n\n render() {\n const { prefix, locale, pure } = this.props;\n\n return (\n <ul>\n <li>prefix: {prefix}</li>\n <li>locale: {JSON.stringify(locale)}</li>\n <li>pure: {pure.toString()}</li>\n </ul>\n );\n }\n}\n\nconst NewOutput = config(Output);\n\nclass Demo extends React.Component {\n render() {\n return (\n <ConfigProvider prefix=\"custom-\" locale={{ Output: { hello: 'hello' } }} pure>\n <NewOutput />\n </ConfigProvider>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
最简单的用法,展示 ConfigProvider 是如何工作的。
\n","order":"1"},"codes":{"jsx":"import { ConfigProvider } from '@alifd/next';\nimport PropTypes from 'prop-types';\n\nconst { config } = ConfigProvider;\n\nclass Output extends React.Component {\n static propTypes = {\n prefix: PropTypes.string,\n locale: PropTypes.object,\n pure: PropTypes.bool\n };\n\n static defaultProps = {\n prefix: 'next-',\n locale: {\n hello: '你好'\n },\n pure: false\n };\n\n render() {\n const { prefix, locale, pure } = this.props;\n\n return (\nimport { ConfigProvider } from '@alifd/next';\nimport PropTypes from 'prop-types';\n\nconst { config } = ConfigProvider;\n\nclass Output extends React.Component {\n static propTypes = {\n prefix: PropTypes.string,\n locale: PropTypes.object,\n pure: PropTypes.bool\n };\n\n static defaultProps = {\n prefix: 'next-',\n locale: {\n hello: '你好'\n },\n pure: false\n };\n\n render() {\n const { prefix, locale, pure } = this.props;\n\n return (\n <ul>\n <li>prefix: {prefix}</li>\n <li>locale: {JSON.stringify(locale)}</li>\n <li>pure: {pure.toString()}</li>\n </ul>\n );\n }\n}\n\nconst NewOutput = config(Output);\n\nclass Demo extends React.Component {\n render() {\n return (\n <ConfigProvider prefix=\"custom-\" locale={{ Output: { hello: 'hello' } }} pure>\n <NewOutput />\n </ConfigProvider>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
Show the components that support internationalization in the current Next components.
\n","order":"2"},"codes":{"jsx":"import { ConfigProvider, Button, Radio, Calendar, Card, DatePicker, Dialog, Pagination, TimePicker, Timeline, Transfer, Select, Upload, Table } from '@alifd/next';\n\nimport enUS from '@alifd/next/lib/locale/en-us';\nimport zhCN from '@alifd/next/lib/locale/zh-cn';\n\n// If the application directly imports the next-with-locales.js file from cdn\n// it need to import locale file in the following way\n// import { locales } from '@alifd/next';\n// const enUS = locales['en-us'];\n// const zhCN = locales['zh-cn'];\n\nconst RangePicker = DatePicker.RangePicker;\n\nconst transferDataSource = (() => {\n const dataSource = [];\n\n for (let i = 0; i < 10; i++) {\n dataSource.push({\n label: `content ${i}`,\n value: `${i}`,\n disabled: i % 4 === 0\n });\n }\n\n return dataSource;\n})();\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n lang: 'en-us'\n };\n\n this.changeLang = this.changeLang.bind(this);\n this.showDialog = this.showDialog.bind(this);\n }\n\n changeLang(lang) {\n this.setState({\n lang\n });\n }\n\n showDialog() {\n Dialog.confirm({\n title: 'Confirm',\n content: 'Are you sure you want to delete all alert e-mails waiting in queue?'\n });\n }\n\n render() {\n const locale = this.state.lang === 'en-us' ? enUS : zhCN;\n\n return (\nimport { ConfigProvider, Button, Radio, Calendar, Card, DatePicker, Dialog, Pagination, TimePicker, Timeline, Transfer, Select, Upload, Table } from '@alifd/next';\n\nimport enUS from '@alifd/next/lib/locale/en-us';\nimport zhCN from '@alifd/next/lib/locale/zh-cn';\n\n// If the application directly imports the next-with-locales.js file from cdn\n// it need to import locale file in the following way\n// import { locales } from '@alifd/next';\n// const enUS = locales['en-us'];\n// const zhCN = locales['zh-cn'];\n\nconst RangePicker = DatePicker.RangePicker;\n\nconst transferDataSource = (() => {\n const dataSource = [];\n\n for (let i = 0; i < 10; i++) {\n dataSource.push({\n label: `content ${i}`,\n value: `${i}`,\n disabled: i % 4 === 0\n });\n }\n\n return dataSource;\n})();\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n lang: 'en-us'\n };\n\n this.changeLang = this.changeLang.bind(this);\n this.showDialog = this.showDialog.bind(this);\n }\n\n changeLang(lang) {\n this.setState({\n lang\n });\n }\n\n showDialog() {\n Dialog.confirm({\n title: 'Confirm',\n content: 'Are you sure you want to delete all alert e-mails waiting in queue?'\n });\n }\n\n render() {\n const locale = this.state.lang === 'en-us' ? enUS : zhCN;\n\n return (\n <div>\n <div className=\"change-locale\">\n <span style={{ marginRight: 16 }}>Change locale of components: </span>\n <Radio.Group shape=\"button\" size=\"large\" defaultValue=\"en-us\" onChange={this.changeLang}>\n <Radio key=\"en\" value=\"en-us\">English</Radio>\n <Radio key=\"cn\" value=\"zh-cn\">中文</Radio>\n </Radio.Group>\n </div>\n <ConfigProvider locale={locale}>\n <div className=\"locale-components\">\n <Button type=\"primary\" onClick={this.showDialog}>Show Dialog</Button>\n <Select style={{ width: '150px' }} dataSource={['hello', 'bye']} />\n <DatePicker />\n <TimePicker />\n <RangePicker />\n <Calendar style={{ width: '350px', padding: '12px', border: '1px solid #C4C6CF', borderRadius: '3px' }} shape=\"card\" />\n <Pagination defaultCurrent={2} />\n <Transfer dataSource={transferDataSource} defaultValue={['3']} defaultLeftChecked={['1']} titles={['Source', 'Target']} />\n <Table style={{ width: '500px' }} dataSource={[]}>\n <Table.Column title=\"Name\" dataIndex=\"name\" filters={[{ label: 'Filter 1', value: '1' }, { label: 'Filter 2', value: '2' }]} />\n <Table.Column title=\"Age\" dataIndex=\"age\" />\n </Table>\n <Card style={{ width: '300px' }} title=\"Title\">\n <div style={{ height: '250px', background: '#F7F8FA' }}></div>\n </Card>\n <Timeline fold={[{foldArea: [1, 2], foldShow: true}]}>\n <Timeline.Item title=\"Signed\" content=\"Signed, sign Alibaba is a small post office, thanks to the use of STO, look forward to once again at your service\" time={'2016-06-10 10:30:00'} state=\"process\"/>\n <Timeline.Item title=\"Ship\" content=\"Express has arrived in Hangzhou, Zhejiang Binjiang company\" time={'2016-06-10 09:30:00'} />\n <Timeline.Item title=\"Ship\" content=\"Zhejiang Hangzhou Riverside company sent a member for you to send pieces\" time={'2016-06-10 09:03:00'} />\n <Timeline.Item title=\"Ship\" content=\"Zhejiang Hangzhou Transshipment Center has been issued\" time={'2016-06-10 06:10:00'} />\n </Timeline>\n <Upload.Dragger style={{ width: '500px' }}\n listType=\"image\"\n action=\"https://www.easy-mock.com/mock/5b713974309d0d7d107a74a3/alifd/upload\"\n accept=\"image/png, image/jpg, image/jpeg, image/gif, image/bmp\" />\n </div>\n </ConfigProvider>\n </div>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
.change-locale {\n border-bottom: 1px solid #d9d9d9;\n padding-bottom: 16px;\n}\n\n.locale-components > * {\n margin: 16px 0;\n display: block;\n}
展示目前 Next 组件中支持国际化的组件。
\n","order":"2"},"codes":{"jsx":"import { ConfigProvider, Button, Radio, Calendar, Card, DatePicker, Dialog, Pagination, TimePicker, Timeline, Transfer, Select, Upload, Table } from '@alifd/next';\n\nimport enUS from '@alifd/next/lib/locale/en-us';\nimport zhCN from '@alifd/next/lib/locale/zh-cn';\n\n// If the application directly imports the next-with-locales.js file from cdn\n// it need to import locale file in the following way\n// import { locales } from '@alifd/next';\n// const enUS = locales['en-us'];\n// const zhCN = locales['zh-cn'];\n\nconst RangePicker = DatePicker.RangePicker;\n\nconst transferDataSource = (() => {\n const dataSource = [];\n\n for (let i = 0; i < 10; i++) {\n dataSource.push({\n label: `content ${i}`,\n value: `${i}`,\n disabled: i % 4 === 0\n });\n }\n\n return dataSource;\n})();\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n lang: 'en-us'\n };\n\n this.changeLang = this.changeLang.bind(this);\n this.showDialog = this.showDialog.bind(this);\n }\n\n changeLang(lang) {\n this.setState({\n lang\n });\n }\n\n showDialog() {\n Dialog.confirm({\n title: 'Confirm',\n content: 'Are you sure you want to delete all alert e-mails waiting in queue?'\n });\n }\n\n render() {\n const locale = this.state.lang === 'en-us' ? enUS : zhCN;\n\n return (\nimport { ConfigProvider, Button, Radio, Calendar, Card, DatePicker, Dialog, Pagination, TimePicker, Timeline, Transfer, Select, Upload, Table } from '@alifd/next';\n\nimport enUS from '@alifd/next/lib/locale/en-us';\nimport zhCN from '@alifd/next/lib/locale/zh-cn';\n\n// If the application directly imports the next-with-locales.js file from cdn\n// it need to import locale file in the following way\n// import { locales } from '@alifd/next';\n// const enUS = locales['en-us'];\n// const zhCN = locales['zh-cn'];\n\nconst RangePicker = DatePicker.RangePicker;\n\nconst transferDataSource = (() => {\n const dataSource = [];\n\n for (let i = 0; i < 10; i++) {\n dataSource.push({\n label: `content ${i}`,\n value: `${i}`,\n disabled: i % 4 === 0\n });\n }\n\n return dataSource;\n})();\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n lang: 'en-us'\n };\n\n this.changeLang = this.changeLang.bind(this);\n this.showDialog = this.showDialog.bind(this);\n }\n\n changeLang(lang) {\n this.setState({\n lang\n });\n }\n\n showDialog() {\n Dialog.confirm({\n title: 'Confirm',\n content: 'Are you sure you want to delete all alert e-mails waiting in queue?'\n });\n }\n\n render() {\n const locale = this.state.lang === 'en-us' ? enUS : zhCN;\n\n return (\n <div>\n <div className=\"change-locale\">\n <span style={{ marginRight: 16 }}>Change locale of components: </span>\n <Radio.Group shape=\"button\" size=\"large\" defaultValue=\"en-us\" onChange={this.changeLang}>\n <Radio key=\"en\" value=\"en-us\">English</Radio>\n <Radio key=\"cn\" value=\"zh-cn\">中文</Radio>\n </Radio.Group>\n </div>\n <ConfigProvider locale={locale}>\n <div className=\"locale-components\">\n <Button type=\"primary\" onClick={this.showDialog}>Show Dialog</Button>\n <Select style={{ width: '150px' }} dataSource={['hello', 'bye']} />\n <DatePicker />\n <TimePicker />\n <RangePicker />\n <Calendar style={{ width: '350px', padding: '12px', border: '1px solid #C4C6CF', borderRadius: '3px' }} shape=\"card\" />\n <Pagination defaultCurrent={2} />\n <Transfer dataSource={transferDataSource} defaultValue={['3']} defaultLeftChecked={['1']} titles={['Source', 'Target']} />\n <Table style={{ width: '500px' }} dataSource={[]}>\n <Table.Column title=\"Name\" dataIndex=\"name\" filters={[{ label: 'Filter 1', value: '1' }, { label: 'Filter 2', value: '2' }]} />\n <Table.Column title=\"Age\" dataIndex=\"age\" />\n </Table>\n <Card style={{ width: '300px' }} title=\"Title\">\n <div style={{ height: '250px', background: '#F7F8FA' }}></div>\n </Card>\n <Timeline fold={[{foldArea: [1, 2], foldShow: true}]}>\n <Timeline.Item title=\"Signed\" content=\"Signed, sign Alibaba is a small post office, thanks to the use of STO, look forward to once again at your service\" time={'2016-06-10 10:30:00'} state=\"process\"/>\n <Timeline.Item title=\"Ship\" content=\"Express has arrived in Hangzhou, Zhejiang Binjiang company\" time={'2016-06-10 09:30:00'} />\n <Timeline.Item title=\"Ship\" content=\"Zhejiang Hangzhou Riverside company sent a member for you to send pieces\" time={'2016-06-10 09:03:00'} />\n <Timeline.Item title=\"Ship\" content=\"Zhejiang Hangzhou Transshipment Center has been issued\" time={'2016-06-10 06:10:00'} />\n </Timeline>\n <Upload.Dragger style={{ width: '500px' }}\n listType=\"image\"\n action=\"https://www.easy-mock.com/mock/5b713974309d0d7d107a74a3/alifd/upload\"\n accept=\"image/png, image/jpg, image/jpeg, image/gif, image/bmp\" />\n </div>\n </ConfigProvider>\n </div>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
.change-locale {\n border-bottom: 1px solid #d9d9d9;\n padding-bottom: 16px;\n}\n\n.locale-components > * {\n margin: 16px 0;\n display: block;\n}
<Consumer>
can be to read context state of <ConfigProvider>
with easly and highly customized
{JSON.stringify(context, false, 2)}\n
{JSON.stringify(context, false, 2)}\n
import { ConfigProvider } from '@alifd/next';\nimport PropTypes from 'prop-types';\n\nconst localeSettings = {\n momentLocale: 'fr-FR',\n CustomizedComponent: {\n helloWorld: 'hello, world'\n }\n};\n\nconst App = ({ children }) => (\n <ConfigProvider\n prefix=\"customized-\"\n locale={localeSettings}\n pure\n warning={false}\n >\n {children}\n </ConfigProvider>\n);\n\nApp.propTypes = {\n children: PropTypes.node\n};\n\nconst Child = () => (\n <ConfigProvider.Consumer>\n {\n context => (\n <div className=\"context-data\">\n <h3>Context's state</h3>\n <pre>{JSON.stringify(context, false, 2)}</pre>\n </div>\n )\n }\n </ConfigProvider.Consumer>\n);\n\nconst Demo = () => (\n <App>\n <Child />\n </App>\n);\n\nReactDOM.render(<Demo />, mountNode);
.context-data {\n padding: 0 32px 32px;\n border: 3px dashed #aaa;\n border-radius: 9px;\n}
使用 <Consumer>
可以方便地读取 <ConfigProvider>
中上下文的数据
{JSON.stringify(context, false, 2)}\n
{JSON.stringify(context, false, 2)}\n
import { ConfigProvider } from '@alifd/next';\nimport PropTypes from 'prop-types';\n\nconst localeSettings = {\n momentLocale: 'fr-FR',\n CustomizedComponent: {\n helloWorld: 'hello, world'\n }\n};\n\nconst App = ({ children }) => (\n <ConfigProvider\n prefix=\"customized-\"\n locale={localeSettings}\n pure\n warning={false}\n >\n {children}\n </ConfigProvider>\n);\n\nApp.propTypes = {\n children: PropTypes.node\n};\n\nconst Child = () => (\n <ConfigProvider.Consumer>\n {\n context => (\n <div className=\"context-data\">\n <h3>Context's state</h3>\n <pre>{JSON.stringify(context, false, 2)}</pre>\n </div>\n )\n }\n </ConfigProvider.Consumer>\n);\n\nconst Demo = () => (\n <App>\n <Child />\n </App>\n);\n\nReactDOM.render(<Demo />, mountNode);
.context-data {\n padding: 0 32px 32px;\n border: 3px dashed #aaa;\n border-radius: 9px;\n}
<ErrorBoundary>
can be used to avoid blank screen caused by local errors
import { ConfigProvider, Button } from '@alifd/next';\n\nconst { ErrorBoundary, config } = ConfigProvider;\n\nclass Demo extends React.Component {\n render() {\n if (this.props.throwError) {\n throw Error('There is something going wrong!');\n } else {\n return (\n <span>normal</span>\n );\n }\n }\n}\n\nconst NewDemo = config(Demo);\n\nconst fallbackUI = (props) => {\n const { error, errorInfo } = props;\n return <span style={{color: 'red'}}>{error.toString()}</span>;\n};\n\nclass App extends React.Component {\n state = {\n throwError: false\n };\n\n onClick = () => {\n this.setState({\n throwError: true\n });\n };\n\n render() {\n return (<div>\n Click to throw an error <Button type=\"primary\" onClick={this.onClick}>trigger error</Button>\n <br/>\n <br/>\n Default fallback UI:\n <hr />\n <ConfigProvider errorBoundary>\n <NewDemo throwError={this.state.throwError}/>\n </ConfigProvider>\n <br/>\n <br/>\n Customize fallback UI of configed Component(Basic Components / Biz Components):\n <hr />\n <ConfigProvider errorBoundary={{\n fallbackUI: props => {\n const { error, errorInfo } = props;\n return <span style={{color: 'red'}}>Error: {error.toString()}</span>;\n },\n afterCatch: () => {\n console.log('catching');\n }\n }}>\n <NewDemo throwError={this.state.throwError}/>\n </ConfigProvider>\n </div>);\n }\n}\n\nReactDOM.render(<App />, mountNode);
使用 <ErrorBoundary>
可以避免由于局部区域的错误,所引起的页面白屏。
import { ConfigProvider, Button } from '@alifd/next';\n\nconst { ErrorBoundary, config } = ConfigProvider;\n\nclass Demo extends React.Component {\n render() {\n if (this.props.throwError) {\n throw Error('There is something going wrong!');\n } else {\n return (\n <span>normal</span>\n );\n }\n }\n}\n\nconst NewDemo = config(Demo);\n\nconst fallbackUI = (props) => {\n const { error, errorInfo } = props;\n return <span style={{color: 'red'}}>{error.toString()}</span>;\n};\n\nclass App extends React.Component {\n state = {\n throwError: false\n };\n\n onClick = () => {\n this.setState({\n throwError: true\n });\n };\n\n render() {\n return (<div>\n Click to throw an error <Button type=\"primary\" onClick={this.onClick}>trigger error</Button>\n <br/>\n <br/>\n Default fallback UI:\n <hr />\n <ConfigProvider errorBoundary>\n <NewDemo throwError={this.state.throwError}/>\n </ConfigProvider>\n <br/>\n <br/>\n Customize fallback UI of configed Component(Basic Components / Biz Components):\n <hr />\n <ConfigProvider errorBoundary={{\n fallbackUI: props => {\n const { error, errorInfo } = props;\n return <span style={{color: 'red'}}>Error: {error.toString()}</span>;\n },\n afterCatch: () => {\n console.log('catching');\n }\n }}>\n <NewDemo throwError={this.state.throwError}/>\n </ConfigProvider>\n </div>);\n }\n}\n\nReactDOM.render(<App />, mountNode);
Demo how to use ConfigProvider to implement components with international capabilities.
\n","order":"0"},"codes":{"jsx":"import { ConfigProvider, Button, Select } from '@alifd/next';\nimport PropTypes from 'prop-types';\n\nconst { config, getContextProps } = ConfigProvider;\nconst { Option } = Select;\n\nconst locales = {\n 'zh-cn': {\n ClickMe: {\n clickMe: '点我!'\n },\n Toast: {\n close: '关闭'\n }\n },\n 'en-us': {\n ClickMe: {\n clickMe: 'click me!'\n },\n Toast: {\n close: 'close'\n }\n }\n};\n\nclass ClickMe extends React.Component {\n static propTypes = {\n locale: PropTypes.object,\n onClick: PropTypes.func\n };\n\n static defaultProps = {\n locale: locales['zh-cn'].ClickMe,\n onClick: () => {}\n };\n\n render() {\n const { locale, onClick } = this.props;\n return (\n \n );\n }\n}\n\nclass Toast extends React.Component {\n static propTypes = {\n locale: PropTypes.object,\n afterClose: PropTypes.func\n };\n\n static defaultProps = {\n locale: locales['zh-cn'].Toast,\n afterClose: () => {}\n };\n\n constructor(props) {\n super(props);\n\n this.state = {\n visible: false\n };\n\n this.handleClose = this.handleClose.bind(this);\n }\n\n handleClose() {\n this.setState({\n visible: false\n });\n this.props.afterClose();\n }\n\n render() {\n return (\nimport { ConfigProvider, Button, Select } from '@alifd/next';\nimport PropTypes from 'prop-types';\n\nconst { config, getContextProps } = ConfigProvider;\nconst { Option } = Select;\n\nconst locales = {\n 'zh-cn': {\n ClickMe: {\n clickMe: '点我!'\n },\n Toast: {\n close: '关闭'\n }\n },\n 'en-us': {\n ClickMe: {\n clickMe: 'click me!'\n },\n Toast: {\n close: 'close'\n }\n }\n};\n\nclass ClickMe extends React.Component {\n static propTypes = {\n locale: PropTypes.object,\n onClick: PropTypes.func\n };\n\n static defaultProps = {\n locale: locales['zh-cn'].ClickMe,\n onClick: () => {}\n };\n\n render() {\n const { locale, onClick } = this.props;\n return (\n <Button onClick={onClick}>{locale.clickMe}</Button>\n );\n }\n}\n\nclass Toast extends React.Component {\n static propTypes = {\n locale: PropTypes.object,\n afterClose: PropTypes.func\n };\n\n static defaultProps = {\n locale: locales['zh-cn'].Toast,\n afterClose: () => {}\n };\n\n constructor(props) {\n super(props);\n\n this.state = {\n visible: false\n };\n\n this.handleClose = this.handleClose.bind(this);\n }\n\n handleClose() {\n this.setState({\n visible: false\n });\n this.props.afterClose();\n }\n\n render() {\n return (\n <div className=\"toast\">\n <Button type=\"primary\" onClick={this.handleClose}>\n {this.props.locale.close}\n </Button>\n </div>\n );\n }\n}\nToast.create = (props = {}) => {\n const mountNode = document.createElement('div');\n document.body.appendChild(mountNode);\n\n const closeChain = () => {\n ReactDOM.unmountComponentAtNode(mountNode);\n document.body.removeChild(mountNode);\n };\n\n const newLocale = getContextProps(props, 'Toast').locale;\n\n ReactDOM.render(<Toast afterClose={closeChain} locale={newLocale} />, mountNode);\n};\n\nconst NewClickMe = config(ClickMe);\nconst NewToast = config(Toast);\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n language: 'zh-cn'\n };\n\n this.handleClick = this.handleClick.bind(this);\n this.handleChangeLanguage = this.handleChangeLanguage.bind(this);\n }\n\n handleClick() {\n NewToast.create();\n }\n\n handleChangeLanguage(language) {\n this.setState({\n language\n });\n }\n\n render() {\n const { language } = this.state;\n\n return (\n <ConfigProvider locale={locales[language]}>\n <div>\n <div className=\"select-language\">\n <Select value={language} onChange={this.handleChangeLanguage}>\n <Option value=\"zh-cn\">zh-cn</Option>\n <Option value=\"en-us\">en-us</Option>\n </Select>\n </div>\n <NewClickMe onClick={this.handleClick} />\n </div>\n </ConfigProvider>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
.toast {\n position: fixed;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n margin: auto;\n width: 200px;\n height: 100px;\n line-height: 100px;\n text-align: center;\n background: white;\n box-shadow: 3px 3px 5px 0 rgba(0, 0, 0, .32);\n}\n\n.toast .next-btn {\n margin: auto;\n}\n\n.select-language {\n margin-bottom: 20px;\n}
展示如何配合 ConfigProvider 实现具有国际化能力的组件。
\n","order":"0"},"codes":{"jsx":"import { ConfigProvider, Button, Select } from '@alifd/next';\nimport PropTypes from 'prop-types';\n\nconst { config, getContextProps } = ConfigProvider;\nconst { Option } = Select;\n\nconst locales = {\n 'zh-cn': {\n ClickMe: {\n clickMe: '点我!'\n },\n Toast: {\n close: '关闭'\n }\n },\n 'en-us': {\n ClickMe: {\n clickMe: 'click me!'\n },\n Toast: {\n close: 'close'\n }\n }\n};\n\nclass ClickMe extends React.Component {\n static propTypes = {\n locale: PropTypes.object,\n onClick: PropTypes.func\n };\n\n static defaultProps = {\n locale: locales['zh-cn'].ClickMe,\n onClick: () => {}\n };\n\n render() {\n const { locale, onClick } = this.props;\n return (\n \n );\n }\n}\n\nclass Toast extends React.Component {\n static propTypes = {\n locale: PropTypes.object,\n afterClose: PropTypes.func\n };\n\n static defaultProps = {\n locale: locales['zh-cn'].Toast,\n afterClose: () => {}\n };\n\n constructor(props) {\n super(props);\n\n this.state = {\n visible: false\n };\n\n this.handleClose = this.handleClose.bind(this);\n }\n\n handleClose() {\n this.setState({\n visible: false\n });\n this.props.afterClose();\n }\n\n render() {\n return (\nimport { ConfigProvider, Button, Select } from '@alifd/next';\nimport PropTypes from 'prop-types';\n\nconst { config, getContextProps } = ConfigProvider;\nconst { Option } = Select;\n\nconst locales = {\n 'zh-cn': {\n ClickMe: {\n clickMe: '点我!'\n },\n Toast: {\n close: '关闭'\n }\n },\n 'en-us': {\n ClickMe: {\n clickMe: 'click me!'\n },\n Toast: {\n close: 'close'\n }\n }\n};\n\nclass ClickMe extends React.Component {\n static propTypes = {\n locale: PropTypes.object,\n onClick: PropTypes.func\n };\n\n static defaultProps = {\n locale: locales['zh-cn'].ClickMe,\n onClick: () => {}\n };\n\n render() {\n const { locale, onClick } = this.props;\n return (\n <Button onClick={onClick}>{locale.clickMe}</Button>\n );\n }\n}\n\nclass Toast extends React.Component {\n static propTypes = {\n locale: PropTypes.object,\n afterClose: PropTypes.func\n };\n\n static defaultProps = {\n locale: locales['zh-cn'].Toast,\n afterClose: () => {}\n };\n\n constructor(props) {\n super(props);\n\n this.state = {\n visible: false\n };\n\n this.handleClose = this.handleClose.bind(this);\n }\n\n handleClose() {\n this.setState({\n visible: false\n });\n this.props.afterClose();\n }\n\n render() {\n return (\n <div className=\"toast\">\n <Button type=\"primary\" onClick={this.handleClose}>\n {this.props.locale.close}\n </Button>\n </div>\n );\n }\n}\nToast.create = (props = {}) => {\n const mountNode = document.createElement('div');\n document.body.appendChild(mountNode);\n\n const closeChain = () => {\n ReactDOM.unmountComponentAtNode(mountNode);\n document.body.removeChild(mountNode);\n };\n\n const newLocale = getContextProps(props, 'Toast').locale;\n\n ReactDOM.render(<Toast afterClose={closeChain} locale={newLocale} />, mountNode);\n};\n\nconst NewClickMe = config(ClickMe);\nconst NewToast = config(Toast);\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n language: 'zh-cn'\n };\n\n this.handleClick = this.handleClick.bind(this);\n this.handleChangeLanguage = this.handleChangeLanguage.bind(this);\n }\n\n handleClick() {\n NewToast.create();\n }\n\n handleChangeLanguage(language) {\n this.setState({\n language\n });\n }\n\n render() {\n const { language } = this.state;\n\n return (\n <ConfigProvider locale={locales[language]}>\n <div>\n <div className=\"select-language\">\n <Select value={language} onChange={this.handleChangeLanguage}>\n <Option value=\"zh-cn\">zh-cn</Option>\n <Option value=\"en-us\">en-us</Option>\n </Select>\n </div>\n <NewClickMe onClick={this.handleClick} />\n </div>\n </ConfigProvider>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
.toast {\n position: fixed;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n margin: auto;\n width: 200px;\n height: 100px;\n line-height: 100px;\n text-align: center;\n background: white;\n box-shadow: 3px 3px 5px 0 rgba(0, 0, 0, .32);\n}\n\n.toast .next-btn {\n margin: auto;\n}\n\n.select-language {\n margin-bottom: 20px;\n}
Show components with RTL(Partial supported currently).
\n","order":"4"},"codes":{"jsx":"import { ConfigProvider, Button, Radio, Menu, Calendar, DatePicker, Dialog, TimePicker, Timeline, Select } from '@alifd/next';\n\nconst { SubMenu, Item, Group, Divider } = Menu;\nconst RangePicker = DatePicker.RangePicker;\n\n// Set global direction to 'rtl'. This affects the whole page\n// ConfigProvider.setDirection('rtl');\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n dir: 'rtl'\n };\n\n this.changeDir = this.changeDir.bind(this);\n this.showDialog = this.showDialog.bind(this);\n }\n\n changeDir(value) {\n this.setState({\n dir: value\n });\n }\n\n showDialog() {\n Dialog.confirm({\n title: 'Confirm',\n content: 'Are you sure you want to delete all alert e-mails waiting in queue?'\n });\n }\n\n render() {\n\n return (\nimport { ConfigProvider, Button, Radio, Menu, Calendar, DatePicker, Dialog, TimePicker, Timeline, Select } from '@alifd/next';\n\nconst { SubMenu, Item, Group, Divider } = Menu;\nconst RangePicker = DatePicker.RangePicker;\n\n// Set global direction to 'rtl'. This affects the whole page\n// ConfigProvider.setDirection('rtl');\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n dir: 'rtl'\n };\n\n this.changeDir = this.changeDir.bind(this);\n this.showDialog = this.showDialog.bind(this);\n }\n\n changeDir(value) {\n this.setState({\n dir: value\n });\n }\n\n showDialog() {\n Dialog.confirm({\n title: 'Confirm',\n content: 'Are you sure you want to delete all alert e-mails waiting in queue?'\n });\n }\n\n render() {\n\n return (\n <div>\n <div className=\"change-rtl\">\n <span style={{ marginRight: 16 }}>Change direction of components: </span>\n <Radio.Group shape=\"button\" size=\"large\" value={this.state.dir} onChange={this.changeDir}>\n <Radio key=\"rtl\" value=\"rtl\">RTL</Radio>\n <Radio key=\"ltr\" value=\"ltr\">LTR</Radio>\n </Radio.Group>\n </div>\n <br />\n <hr />\n <ConfigProvider rtl={this.state.dir === 'rtl'}>\n <div className=\"locale-components\" dir={this.state.dir}>\n <Button type=\"primary\" onClick={this.showDialog}>Show Dialog</Button>\n <Select style={{ width: '150px' }} dataSource={['hello', 'bye']} />\n <RangePicker showTime/>\n <Calendar style={{ width: '350px', padding: '12px', border: '1px solid #C4C6CF', borderRadius: '3px' }} shape=\"card\" />\n\n <Timeline fold={[{foldArea: [1, 2], foldShow: true}]}>\n <Timeline.Item title=\"Signed\" content=\"Signed, sign Alibaba is a small post office, thanks to the use of STO, look forward to once again at your service\" time={'2016-06-10 10:30:00'} state=\"process\"/>\n <Timeline.Item title=\"Ship\" content=\"Express has arrived in Hangzhou, Zhejiang Binjiang company\" time={'2016-06-10 09:30:00'} />\n <Timeline.Item title=\"Ship\" content=\"Zhejiang Hangzhou Riverside company sent a member for you to send pieces\" time={'2016-06-10 09:03:00'} />\n <Timeline.Item title=\"Ship\" content=\"Zhejiang Hangzhou Transshipment Center has been issued\" time={'2016-06-10 06:10:00'} />\n </Timeline>\n\n <Menu className=\"my-menu\" defaultOpenKeys=\"sub-menu\">\n <Item key=\"1\">Option 1</Item>\n <Item disabled key=\"2\">Disabled option 2</Item>\n <Divider key=\"divider\" />\n <Group label=\"Group\">\n <Item key=\"group-1\">Group option 1</Item>\n <Item key=\"group-2\">Group option 2</Item>\n </Group>\n <Divider />\n <SubMenu key=\"sub-menu\" label=\"Sub menu\">\n <Item key=\"sub-1\">Sub option 1</Item>\n <Item key=\"sub-2\">Sub option 2</Item>\n <Item disabled key=\"sub-3\">\n <a href=\"https://www.taobao.com/\" target=\"__blank\">Disabled Option Link 3</a>\n </Item>\n <Item key=\"sub-4\">\n <a href=\"https://www.taobao.com/\" target=\"__blank\">Option Link 4</a>\n </Item>\n </SubMenu>\n <Item key=\"3\" helper=\"CTRL+P\">Option 3</Item>\n <Item disabled key=\"4\">\n <a href=\"https://www.taobao.com/\" target=\"__blank\">Disabled Option Link</a>\n </Item>\n <Item key=\"5\">\n <a href=\"https://www.taobao.com/\" target=\"__blank\">Option Link</a>\n </Item>\n </Menu>\n </div>\n </ConfigProvider>\n </div>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
.my-menu {\n width: 200px;\n}\n\n.change-locale {\n border-bottom: 1px solid #d9d9d9;\n padding-bottom: 16px;\n}\n\n.locale-components > * {\n margin: 16px 0;\n display: block;\n}
组件RTL样式展示(目前部分支持)
\n","order":"4"},"codes":{"jsx":"import { ConfigProvider, Button, Radio, Menu, Calendar, DatePicker, Dialog, TimePicker, Timeline, Select } from '@alifd/next';\n\nconst { SubMenu, Item, Group, Divider } = Menu;\nconst RangePicker = DatePicker.RangePicker;\n\n// Set global direction to 'rtl'. This affects the whole page\n// ConfigProvider.setDirection('rtl');\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n dir: 'rtl'\n };\n\n this.changeDir = this.changeDir.bind(this);\n this.showDialog = this.showDialog.bind(this);\n }\n\n changeDir(value) {\n this.setState({\n dir: value\n });\n }\n\n showDialog() {\n Dialog.confirm({\n title: 'Confirm',\n content: 'Are you sure you want to delete all alert e-mails waiting in queue?'\n });\n }\n\n render() {\n\n return (\nimport { ConfigProvider, Button, Radio, Menu, Calendar, DatePicker, Dialog, TimePicker, Timeline, Select } from '@alifd/next';\n\nconst { SubMenu, Item, Group, Divider } = Menu;\nconst RangePicker = DatePicker.RangePicker;\n\n// Set global direction to 'rtl'. This affects the whole page\n// ConfigProvider.setDirection('rtl');\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n dir: 'rtl'\n };\n\n this.changeDir = this.changeDir.bind(this);\n this.showDialog = this.showDialog.bind(this);\n }\n\n changeDir(value) {\n this.setState({\n dir: value\n });\n }\n\n showDialog() {\n Dialog.confirm({\n title: 'Confirm',\n content: 'Are you sure you want to delete all alert e-mails waiting in queue?'\n });\n }\n\n render() {\n\n return (\n <div>\n <div className=\"change-rtl\">\n <span style={{ marginRight: 16 }}>Change direction of components: </span>\n <Radio.Group shape=\"button\" size=\"large\" value={this.state.dir} onChange={this.changeDir}>\n <Radio key=\"rtl\" value=\"rtl\">RTL</Radio>\n <Radio key=\"ltr\" value=\"ltr\">LTR</Radio>\n </Radio.Group>\n </div>\n <br />\n <hr />\n <ConfigProvider rtl={this.state.dir === 'rtl'}>\n <div className=\"locale-components\" dir={this.state.dir}>\n <Button type=\"primary\" onClick={this.showDialog}>Show Dialog</Button>\n <Select style={{ width: '150px' }} dataSource={['hello', 'bye']} />\n <RangePicker showTime/>\n <Calendar style={{ width: '350px', padding: '12px', border: '1px solid #C4C6CF', borderRadius: '3px' }} shape=\"card\" />\n\n <Timeline fold={[{foldArea: [1, 2], foldShow: true}]}>\n <Timeline.Item title=\"Signed\" content=\"Signed, sign Alibaba is a small post office, thanks to the use of STO, look forward to once again at your service\" time={'2016-06-10 10:30:00'} state=\"process\"/>\n <Timeline.Item title=\"Ship\" content=\"Express has arrived in Hangzhou, Zhejiang Binjiang company\" time={'2016-06-10 09:30:00'} />\n <Timeline.Item title=\"Ship\" content=\"Zhejiang Hangzhou Riverside company sent a member for you to send pieces\" time={'2016-06-10 09:03:00'} />\n <Timeline.Item title=\"Ship\" content=\"Zhejiang Hangzhou Transshipment Center has been issued\" time={'2016-06-10 06:10:00'} />\n </Timeline>\n\n <Menu className=\"my-menu\" defaultOpenKeys=\"sub-menu\">\n <Item key=\"1\">Option 1</Item>\n <Item disabled key=\"2\">Disabled option 2</Item>\n <Divider key=\"divider\" />\n <Group label=\"Group\">\n <Item key=\"group-1\">Group option 1</Item>\n <Item key=\"group-2\">Group option 2</Item>\n </Group>\n <Divider />\n <SubMenu key=\"sub-menu\" label=\"Sub menu\">\n <Item key=\"sub-1\">Sub option 1</Item>\n <Item key=\"sub-2\">Sub option 2</Item>\n <Item disabled key=\"sub-3\">\n <a href=\"https://www.taobao.com/\" target=\"__blank\">Disabled Option Link 3</a>\n </Item>\n <Item key=\"sub-4\">\n <a href=\"https://www.taobao.com/\" target=\"__blank\">Option Link 4</a>\n </Item>\n </SubMenu>\n <Item key=\"3\" helper=\"CTRL+P\">Option 3</Item>\n <Item disabled key=\"4\">\n <a href=\"https://www.taobao.com/\" target=\"__blank\">Disabled Option Link</a>\n </Item>\n <Item key=\"5\">\n <a href=\"https://www.taobao.com/\" target=\"__blank\">Option Link</a>\n </Item>\n </Menu>\n </div>\n </ConfigProvider>\n </div>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
.my-menu {\n width: 200px;\n}\n\n.change-locale {\n border-bottom: 1px solid #d9d9d9;\n padding-bottom: 16px;\n}\n\n.locale-components > * {\n margin: 16px 0;\n display: block;\n}
Now support four languages: Simplified Chinese, Traditional Chinese, English and Japanese.
\nimport { ConfigProvider, DatePicker } from '@alifd/next';\nimport enUS from '@alifd/next/lib/locale/en-us';\n// import zhCN from '@alifd/next/lib/locale/zh-cn';\n// import zhTW from '@alifd/next/lib/locale/zh-tw';\n// import jaJP from '@alifd/next/lib/locale/ja-jp';\n\n// If the application directly imports the next-with-locales.js file from cdn\n// it need to import locale file in the following way\n// const { ConfigProvider, DatePicker, locales } = window.Next;\n// const enUS = locales['en-us'];\n\n\nclass App extends React.Component {\n render() {\n return (\n <ConfigProvider locale={enUS}>\n <DatePicker />\n </ConfigProvider>\n );\n }\n}
The passed locale object has the following format:
\n{\n DatePicker: {\n datePlaceholder: 'Select date',\n monthPlaceholder: 'Select month',\n yearPlaceholder: 'Select year',\n rangeStartPlaceholder: 'Start date',\n rangeEndPlaceholder: 'End date',\n ok: 'OK',\n clear: 'Clear'\n },\n Dialog: {\n // ...\n },\n // ...\n}
Wrapper ConfigProvider for your application and set the custom prefix
\nentry.jsx
\nclass App extends React.Component {\n render() {\n return (\n <ConfigProvider prefix="my-">\n <div>\n <Input />\n <Button>Submit</Button>\n </div>\n </ConfigProvider>\n );\n }\n}
Set the $css-prefix
to the same value before importing the theme scss file in the scss entry file.
entry.scss
\n$css-prefix: "my-";\n@import "~@alifd/theme-xxx/index.scss";
import { ConfigProvider, DatePicker } from '@alifd/next';\n\nclass App extends React.Component {\n render() {\n return (\n <ConfigProvider pure>\n <DatePicker />\n </ConfigProvider>\n );\n }\n}
import { ConfigProvider } from '@alifd/next';\nimport locale from './locale';\n\nconst { config } = ConfigProvider;\n\nclass Component extends React.Component {\n static propTypes = {\n prefix: PropTypes.string,\n locale: PropTypes.object,\n pure: PropTypes.bool\n };\n\n static defaultProps = {\n prefix: 'next-',\n locale: locale,\n pure: false\n };\n\n render() {\n const { prefix, locale, pure } = this.props;\n // ...\n }\n}\n\nexport default config(Component);
Param | \nDescription | \nType | \nDefault Value | \n
---|---|---|---|
errorBoundary | \nturn errorBoundary on or not If you pass object, properties: fallbackUI Function(error?: {}, errorInfo?: {}) => Element afterCatch Function(error?: {}, errorInfo?: {}) after being catched, e.g. send data to server for data statistics | \nBoolean/Object | \nfalse | \n
pure | \nwhether enable the Pure Render mode, it will improve performance, but it will also have side effects | \nBoolean | \n- | \n
device | \nResponsive of device Options: desktop , tablet , phone | \n- | \n|
warning | \nwhether to display the warning prompt for component properties being deprecated in development mode | \nBoolean | \ntrue | \n
children | \ncomponent tree | \nReactElement | \n- | \n
popupContainer | \nshell container node | \nString/Function | \n- | \n
Pass the component and generate the HOC that is controlled by the ConfigProvider. If the component does not declare the shouldComponentUpdate method, the following shouldComponentUpdate method is added to support the pure property of the ConfigProvider.
\nComponent.prototype.shouldComponentUpdate = function shouldComponentUpdate(nextProps, nextState) {\n if (this.props.pure) {\n return !shallowEqual(this.props, nextProps) || !shallowEqual(this.state, nextState);\n }\n\n return true;\n};
Pass the props and displayName of the component to get the object containing preifx/locale/pure calculated by childContext, it is generally used to generate components that are separated from the component tree through static methods.
\nYou can get the context of ConfigProvider via this method. The format of the value returned as follows. For multiple ConfigProvider nested, the results will be merged and the nearer the higher priority。
\n{\n prefix: nextPrefix,\n locale: nextLocale,\n pure: nextPure,\n warning: nextWarning\n}
Config locales, together with method ConfigProvider.setLanguage
to specify the language package
ConfigProvider.initLocales({\n 'zh-cn': {},\n 'en-us': {}\n});
Set language, the parameter language
needs to be one of the keys of locales
which is the input of ConfigProvider.initLocales
. zh-cn
by default.
ConfigProvider.setLanguage('zh-cn');
Set language package directly.
\n// The effect is the same as using ConfigProvider.initLocales and ConfigProvider.setLanguage\nConfigProvider.setLocale({\n DatePicker: {},\n Dialog: {}\n});
Set dir, when it is rtl
, dir="rtl"
will be added on the DOM element of each component's root node.
ConfigProvider.setDirection('rtl');
Return the setted language package.
\nReturn the language's name.
\nReturn the direction.
\n\nNext 1.x will use moment as its peerDependencies instead of dependencies, so the user needs to import the moment's cdn file moment-with-locales.js or the local moment module into his own application. For the latter, due to the moment has such code: require('./locale/' + name)
to import locale files, if built with webpack, it will be packaged into all locale files to increase the size of files. There are two main solutions in the current community:
const webpack = require('webpack');\n\nmodule.exports = {\n // ...\n plugins: [\n // Package the specified language files\n new webpack.ContextReplacementPlugin(/moment[\\/\\\\]locale$/, /zh-cn|ja/)\n // Only package the language files referenced, and should add `import 'moment/locale/zh-cn';` in the application\n // new webpack.IgnorePlugin(/^\\.\\/locale$/, /moment$/)\n ]\n};
ConfigProvider use a Component's displayName or name to get its locale. However, the name of the function may be modified in the process of compression and uglifying. Therefore, if you want to support multi-language, you shoul add displayName to the component manually:
\nclass CustomComponent extends React.Component {\n static displayName = 'CustomComponent';\n // ...\n}
Or use babel-plugin-transform-react-es6-displayname
to add displayName during compilation automatically.
Due to the limit of the HOC itself, we can't get the reference of an internal component and call some of its internal methods as below:
\nclass App extends React.Component {\n componentDidMount() {\n // throw an error\n this.refs.hoc.someMethod();\n }\n\n render() {\n return <HOC ref="hoc" />;\n }\n}
To solve this problem, we provide a method called getInstance of the HOC generated by calling the config method. You can call it as below:
\nclass App extends React.Component {\n componentDidMount() {\n this.refs.hoc.getInstance().someMethod();\n }\n\n render() {\n return <HOC ref="hoc" />;\n }\n}
通过 <ConfigProvider locale={localeObj}>
传入语言包,以支持多语言。目前 Fusion 内置的 locale 库支持中英繁日四种语言,覆盖各组件的简单词汇,例如:确定、取消、展开、收起、下一页等, 简单词汇映射表可参考 https://unpkg.com/@alifd/next/lib/locale/\n
\n(ConfigProvider 提供简单组件简单词汇国际化能力,由于日期时间的国际化较为特殊,例如中国的日历是从周一到周日,美国的日历是从周日到周六等,时间相关的组件如DatePicker等需要国际化,请查看相应组件文档。)\n
可通过两种方式设置多语言文案,两种方式接收的对象格式略有不同:
\n{\n key1: value1,\n key2: value2\n}
{\n component1: {\n key1: value1,\n key2: value2\n },\n component2: {\n key1: value1,\n key2: value2\n }\n}
优先级顺序为: 组件自身 locale > 最近 ConfigProvider 的 locale > 更远父级 ConfigProvider 的 locale
\n(注: 由于Dialog.show()
Message.show()
等函数式方法的特殊性,他们的将默认读取页面上的root context。当页面上有多个包含<ConfigProvider/>
的 ReactDOM.render()
方法调用时,由第一个渲染的决定root context)
import { ConfigProvider, DatePicker } from '@alifd/next';\n\nconst localeDatePicker = {\n placeholder: 'localeDatePicker placeholder'\n};\n\nconst localeGlobal = {\n DatePicker: {\n placeholder: 'localeGlobal placeholder'\n }\n};\n\nclass App extends React.Component {\n render() {\n return (\n <div>\n <ConfigProvider locale={localeGlobal}>\n <DatePicker /> should be 'localeGlobal placeholder'\n </ConfigProvider>\n <br />\n <br />\n <ConfigProvider locale={localeGlobal}>\n <DatePicker locale={localeDatePicker} /> should be 'localeDatePicker placeholder'\n </ConfigProvider>\n </div>\n );\n }\n}
根据引入组件库方式的不同(CDN直接引用、作为依赖引用),使用语言包的方式略有差异,具体见如下代码:\n
import { ConfigProvider, DatePicker } from '@alifd/next';\nimport enUS from '@alifd/next/lib/locale/en-us';\n// import zhCN from '@alifd/next/lib/locale/zh-cn';\n// import zhTW from '@alifd/next/lib/locale/zh-tw';\n// import jaJP from '@alifd/next/lib/locale/ja-jp';\n\n// 如果应用中直接引入的是 cdn 上的 next-with-locales.js 文件\n// 需要按照下面的方式引入国际化文案文件\n// const { ConfigProvider, DatePicker, locales } = window.Next;\n// const enUS = locales['en-us'];\n\n\nclass App extends React.Component {\n render() {\n return (\n <ConfigProvider locale={enUS}>\n <DatePicker />\n </ConfigProvider>\n );\n }\n}
如果内置的 locale 库不满足你的需求(比如想支持法语、德语、西班牙语),你也可以参考 https://unpkg.com/@alifd/next/lib/locale/ 来自定义语言包,按照如下格式传入给 locale 即可:
\n{\n DatePicker: {\n datePlaceholder: 'Select date',\n monthPlaceholder: 'Select month',\n yearPlaceholder: 'Select year',\n rangeStartPlaceholder: 'Start date',\n rangeEndPlaceholder: 'End date',\n ok: 'OK',\n clear: 'Clear'\n },\n Dialog: {\n // ...\n },\n // ...\n}
为你的应用包裹 ConfigProvider,并设置相应的 prefix
\nentry.jsx
\nclass App extends React.Component {\n render() {\n return (\n <ConfigProvider prefix="my-">\n <div>\n <Input />\n <Button>Submit</Button>\n </div>\n </ConfigProvider>\n );\n }\n}
scss 入口文件中在引入主题 scss 文件前,设置相应的 $css-prefix
entry.scss
\n$css-prefix: "my-";\n@import "~@alifd/theme-xxx/index.scss";
import { ConfigProvider, DatePicker } from '@alifd/next';\n\nclass App extends React.Component {\n render() {\n return (\n <ConfigProvider pure>\n <DatePicker />\n </ConfigProvider>\n );\n }\n}
import { ConfigProvider } from '@alifd/next';\nimport locale from './locale';\n\nconst { config } = ConfigProvider;\n\nclass Component extends React.Component {\n static propTypes = {\n prefix: PropTypes.string,\n locale: PropTypes.object,\n pure: PropTypes.bool\n };\n\n static defaultProps = {\n prefix: 'next-',\n locale: locale,\n pure: false\n };\n\n render() {\n const { prefix, locale, pure } = this.props;\n // ...\n }\n}\n\nexport default config(Component);
参数 | \n说明 | \n类型 | \n默认值 | \n
---|---|---|---|
errorBoundary | \n是否开启错误捕捉 errorBoundary 如需自定义参数,请传入对象 对象接受参数列表如下: fallbackUI Function(error?: {}, errorInfo?: {}) => Element 捕获错误后的展示afterCatch Function(error?: {}, errorInfo?: {}) 捕获错误后的行为, 比如埋点上传 | \nBoolean/Object | \nfalse | \n
pure | \n是否开启 Pure Render 模式,会提高性能,但是也会带来副作用 | \nBoolean | \n- | \n
warning | \n是否在开发模式下显示组件属性被废弃的 warning 提示 | \nBoolean | \ntrue | \n
rtl | \n是否开启 rtl 模式 | \nBoolean | \n- | \n
device | \n设备类型,针对不同的设备类型组件做出对应的响应式变化 可选值: 'tablet', 'desktop', 'phone' | \nEnum | \n- | \n
children | \n组件树 | \nReactElement | \n- | \n
popupContainer | \n指定浮层渲染的父节点, 可以为节点id的字符串,也可以返回节点的函数 | \nString/Function | \n- | \n
传入组件,生成受 ConfigProvider 控制的 HOC 组件,如果组件没有声明 shouldComponentUpdate 方法,会添加如下 shouldComponentUpdate 方法以支持 ConfigProvider 的 pure 属性
\nComponent.prototype.shouldComponentUpdate = function shouldComponentUpdate(nextProps, nextState) {\n if (this.props.pure) {\n return !shallowEqual(this.props, nextProps) || !shallowEqual(this.state, nextState);\n }\n\n return true;\n};
传入组件的 props 和 displayName,得到和 childContext 计算过的包含有 preifx/locale/pure 的对象,一般用于通过静态方法生成脱离组件树的组件。
\n通过该方法可以获取到 ConfigProvider 的上下文,格式如下。若有多层级 ConfigProvider 嵌套,会返回merge后的结果,关系近的优先。
\n{\n prefix: nextPrefix,\n locale: nextLocale,\n pure: nextPure,\n warning: nextWarning\n}
配置所有语言包, 可配合 ConfigProvider.setLanguage
方法,确定组件使用的语言包。
ConfigProvider.initLocales({\n 'zh-cn': {},\n 'en-us': {}\n});
设置语言,参数 language
需要能在 ConfigProvider.initLocales
方法传入的参数的 key 中找到, 默认为 zh-cn
ConfigProvider.setLanguage('zh-cn');
直接设置语言包
\n// 相当于 同时用ConfigProvider.initLocales 和 ConfigProvider.setLanguage\nConfigProvider.setLocale({\n DatePicker: {},\n Dialog: {}\n});
设置组件展示方向,当传入 rtl
时,会在组件的根DOM节点加上 dir="rtl"
,同时组件展示rtl视觉。可用于阿拉伯等阅读顺序从右到左的国家。
ConfigProvider.setDirection('rtl');
获取当前的语言包
\n获取当前设定的语言
\n获取当前设定的方向
\n\nNext 1.x 中将 moment 作为自己的 peerDependencies 而非 dependencies,所以用户需要自己在应用中引入 moment 的 cdn 文件 moment-with-locales.js 或者本地安装 moment 打包进自己的应用。对于后者,由于 moment 在引入 locale 文件时存在这样的代码:require('./locale/' + name)
,如果用 webpack 构建,会打包进所有的 locale 文件,增加构建后文件的体积,目前社区比较主流的解决方案有以下两种:
const webpack = require('webpack');\n\nmodule.exports = {\n // ...\n plugins: [\n // 打包指定需要的语言文件\n new webpack.ContextReplacementPlugin(/moment[\\/\\\\]locale$/, /zh-cn|ja/)\n // 只打包有过引用的语言文件,应用中需要添加如:`import 'moment/locale/zh-cn';`\n // new webpack.IgnorePlugin(/^\\.\\/locale$/, /moment$/)\n ]\n};
ConfigProvider 获取组件对应的多语言文案,是通过组件的 displayName 或者 name 获取的,但是压缩混淆的过程中有可能会修改函数的 name,因此如果想支持在 ConfigProvider 下实现切换多语言切换,请为组件如下手动添加 displayName:
\nclass CustomComponent extends React.Component {\n static displayName = 'CustomComponent';\n // ...\n}
或者使用 babel-plugin-transform-react-es6-displayname
自动在编译期间添加 displayname。
由于 HOC 本身的限制,我们不能直接像下面代码那样获取内部组件的引用,从而调用它的一些内部方法:
\nclass App extends React.Component {\n componentDidMount() {\n // 报错\n this.refs.hoc.someMethod();\n }\n\n render() {\n return <HOC ref="hoc" />;\n }\n}
为了解决这个问题,我们为调用 config 方法生成的 HOC 组件添加了 getInstance 方法,你可以如下调用:
\nclass App extends React.Component {\n componentDidMount() {\n this.refs.hoc.getInstance().someMethod();\n }\n\n render() {\n return <HOC ref="hoc" />;\n }\n}
Support manual input or keyboard operation,Please refer to ARIA and KeyBoard
.
import { DatePicker } from '@alifd/next';\n\nconst { RangePicker, MonthPicker, YearPicker } = DatePicker;\nconst onChange = val => console.log(val);\n\nReactDOM.render(<div>\n <DatePicker dateInputAriaLabel=\"date input\" inputProps={{\"aria-label\": \"date picker main\"}} onChange={onChange} /> <br /><br />\n <RangePicker startDateInputAriaLabel=\"start date\" startTimeInputAriaLabel=\"start time\" endDateInputAriaLabel=\"end date\" endTimeInputAriaLabel=\"end time\" onChange={onChange} inputProps={{\"aria-label\": \"range picker main\"}} />\n</div>, mountNode);
支持手动输入或键盘操作,请参考ARIA and KeyBoard
。
import { DatePicker } from '@alifd/next';\n\nconst { RangePicker, MonthPicker, YearPicker } = DatePicker;\nconst onChange = val => console.log(val);\n\nReactDOM.render(<div>\n <DatePicker dateInputAriaLabel=\"date input\" inputProps={{\"aria-label\": \"date picker main\"}} onChange={onChange} /> <br /><br />\n <RangePicker startDateInputAriaLabel=\"start date\" startTimeInputAriaLabel=\"start time\" endDateInputAriaLabel=\"end date\" endTimeInputAriaLabel=\"end time\" onChange={onChange} inputProps={{\"aria-label\": \"range picker main\"}} />\n</div>, mountNode);
A basic usage case.
\n","order":"0"},"codes":{"jsx":"import { DatePicker } from '@alifd/next';\n\nconst { RangePicker, MonthPicker, YearPicker } = DatePicker;\nconst onChange = val => console.log(val);\n\nReactDOM.render(import { DatePicker } from '@alifd/next';\n\nconst { RangePicker, MonthPicker, YearPicker } = DatePicker;\nconst onChange = val => console.log(val);\n\nReactDOM.render(<div>\n <DatePicker onChange={onChange} /> <br /><br />\n <MonthPicker onChange={onChange} /> <br /><br />\n <YearPicker onChange={onChange} /> <br /><br />\n <RangePicker onChange={onChange} />\n</div>, mountNode);
最基本的用法。可以通过 onChange
监听选中值的变化。
import { DatePicker } from '@alifd/next';\n\nconst { RangePicker, MonthPicker, YearPicker } = DatePicker;\nconst onChange = val => console.log(val);\n\nReactDOM.render(<div>\n <DatePicker onChange={onChange} /> <br /><br />\n <MonthPicker onChange={onChange} /> <br /><br />\n <YearPicker onChange={onChange} /> <br /><br />\n <RangePicker onChange={onChange} />\n</div>, mountNode);
Create your own RangePicker with two DatePickers.
\n","order":"8"},"codes":{"jsx":"import { DatePicker } from '@alifd/next';\n\nclass CustomRangePicker extends React.Component {\n constructor(props, context) {\n super(props, context);\n this.state = {\n startValue: null,\n endValue: null,\n endOpen: false\n };\n }\n\n disabledStartDate = (startValue) => {\n const { endValue } = this.state;\n if (!startValue || !endValue) {\n return false;\n }\n return startValue.valueOf() > endValue.valueOf();\n }\n\n disabledEndDate = (endValue) => {\n const { startValue } = this.state;\n if (!endValue || !startValue) {\n return false;\n }\n return endValue.valueOf() <= startValue.valueOf();\n }\n\n onChange = (stateName, value) => {\n this.setState({\n [stateName]: value\n });\n }\n\n onStartChange = (value) => {\n this.onChange('startValue', value);\n }\n\n onEndChange = value => {\n this.onChange('endValue', value);\n }\n\n handleStartOpenChange = (open) => {\n if (!open) {\n this.setState({ endOpen: true });\n }\n }\n\n handleEndOpenChange = (open) => {\n this.setState({ endOpen: open });\n }\n\n render() {\n const { endOpen } = this.state;\n return (\nimport { DatePicker } from '@alifd/next';\n\nclass CustomRangePicker extends React.Component {\n constructor(props, context) {\n super(props, context);\n this.state = {\n startValue: null,\n endValue: null,\n endOpen: false\n };\n }\n\n disabledStartDate = (startValue) => {\n const { endValue } = this.state;\n if (!startValue || !endValue) {\n return false;\n }\n return startValue.valueOf() > endValue.valueOf();\n }\n\n disabledEndDate = (endValue) => {\n const { startValue } = this.state;\n if (!endValue || !startValue) {\n return false;\n }\n return endValue.valueOf() <= startValue.valueOf();\n }\n\n onChange = (stateName, value) => {\n this.setState({\n [stateName]: value\n });\n }\n\n onStartChange = (value) => {\n this.onChange('startValue', value);\n }\n\n onEndChange = value => {\n this.onChange('endValue', value);\n }\n\n handleStartOpenChange = (open) => {\n if (!open) {\n this.setState({ endOpen: true });\n }\n }\n\n handleEndOpenChange = (open) => {\n this.setState({ endOpen: open });\n }\n\n render() {\n const { endOpen } = this.state;\n return (\n <div>\n <DatePicker\n disabledDate={this.disabledStartDate}\n placeholder=\"Departure Date\"\n onChange={this.onStartChange}\n onVisibleChange={this.handleStartOpenChange}\n />\n <span className=\"custom-sep\">-</span>\n <DatePicker\n disabledDate={this.disabledEndDate}\n placeholder=\"Return Date\"\n onChange={this.onEndChange}\n visible={endOpen}\n onVisibleChange={this.handleEndOpenChange}\n />\n </div>\n );\n }\n}\n\nReactDOM.render(<div>\n <CustomRangePicker />\n</div>, mountNode);
.custom-sep {\n margin: 0 6px;\n color: #999;\n}
如果默认的 RangePicker 在交互上无法满足您的使用需求,还可以基于 DatePicker 封装实现类似的功能。\n例如,示例中的日期选择可以自由的更改开始或结束日期,而不必每次选择时重置日期。
\n","order":"8"},"codes":{"jsx":"import { DatePicker } from '@alifd/next';\n\nclass CustomRangePicker extends React.Component {\n constructor(props, context) {\n super(props, context);\n this.state = {\n startValue: null,\n endValue: null,\n endOpen: false\n };\n }\n\n disabledStartDate = (startValue) => {\n const { endValue } = this.state;\n if (!startValue || !endValue) {\n return false;\n }\n return startValue.valueOf() > endValue.valueOf();\n }\n\n disabledEndDate = (endValue) => {\n const { startValue } = this.state;\n if (!endValue || !startValue) {\n return false;\n }\n return endValue.valueOf() <= startValue.valueOf();\n }\n\n onChange = (stateName, value) => {\n this.setState({\n [stateName]: value\n });\n }\n\n onStartChange = (value) => {\n this.onChange('startValue', value);\n }\n\n onEndChange = value => {\n this.onChange('endValue', value);\n }\n\n handleStartOpenChange = (open) => {\n if (!open) {\n this.setState({ endOpen: true });\n }\n }\n\n handleEndOpenChange = (open) => {\n this.setState({ endOpen: open });\n }\n\n render() {\n const { endOpen } = this.state;\n return (\nimport { DatePicker } from '@alifd/next';\n\nclass CustomRangePicker extends React.Component {\n constructor(props, context) {\n super(props, context);\n this.state = {\n startValue: null,\n endValue: null,\n endOpen: false\n };\n }\n\n disabledStartDate = (startValue) => {\n const { endValue } = this.state;\n if (!startValue || !endValue) {\n return false;\n }\n return startValue.valueOf() > endValue.valueOf();\n }\n\n disabledEndDate = (endValue) => {\n const { startValue } = this.state;\n if (!endValue || !startValue) {\n return false;\n }\n return endValue.valueOf() <= startValue.valueOf();\n }\n\n onChange = (stateName, value) => {\n this.setState({\n [stateName]: value\n });\n }\n\n onStartChange = (value) => {\n this.onChange('startValue', value);\n }\n\n onEndChange = value => {\n this.onChange('endValue', value);\n }\n\n handleStartOpenChange = (open) => {\n if (!open) {\n this.setState({ endOpen: true });\n }\n }\n\n handleEndOpenChange = (open) => {\n this.setState({ endOpen: open });\n }\n\n render() {\n const { endOpen } = this.state;\n return (\n <div>\n <DatePicker\n disabledDate={this.disabledStartDate}\n placeholder=\"Departure Date\"\n onChange={this.onStartChange}\n onVisibleChange={this.handleStartOpenChange}\n />\n <span className=\"custom-sep\">-</span>\n <DatePicker\n disabledDate={this.disabledEndDate}\n placeholder=\"Return Date\"\n onChange={this.onEndChange}\n visible={endOpen}\n onVisibleChange={this.handleEndOpenChange}\n />\n </div>\n );\n }\n}\n\nReactDOM.render(<div>\n <CustomRangePicker />\n</div>, mountNode);
.custom-sep {\n margin: 0 6px;\n color: #999;\n}
Change default visible month by setting defaultVisibleMonth
or defaultVisibleYear
.
Setting last month as default visible month
\nSetting 2017 as default visible year
\nSetting last month as default visible month
\nSetting 2017 as default visible year
\nimport { DatePicker } from '@alifd/next';\nimport moment from 'moment';\n\nconst { RangePicker, MonthPicker } = DatePicker;\n\nfunction onVisibleMonthChange(val, reason) {\n console.log(val.format('L'), reason);\n}\n\nReactDOM.render(<div>\n <p>Setting last month as default visible month</p>\n <DatePicker defaultVisibleMonth={() => moment().add(-1, 'months')} onVisibleMonthChange={onVisibleMonthChange} />\n <br /><br />\n <RangePicker defaultVisibleMonth={() => moment().add(-1, 'months')} onVisibleMonthChange={onVisibleMonthChange} />\n <br /><br />\n <p>Setting 2017 as default visible year</p>\n <MonthPicker defaultVisibleYear={() => moment('2017', 'YYYY')} />\n</div>, mountNode);
可以通过 defaultVisibleMonth
或 defaultVisibleYear
属性可以修改面板的默认展现日期。
Setting last month as default visible month
\nSetting 2017 as default visible year
\nSetting last month as default visible month
\nSetting 2017 as default visible year
\nimport { DatePicker } from '@alifd/next';\nimport moment from 'moment';\n\nconst { RangePicker, MonthPicker } = DatePicker;\n\nfunction onVisibleMonthChange(val, reason) {\n console.log(val.format('L'), reason);\n}\n\nReactDOM.render(<div>\n <p>Setting last month as default visible month</p>\n <DatePicker defaultVisibleMonth={() => moment().add(-1, 'months')} onVisibleMonthChange={onVisibleMonthChange} />\n <br /><br />\n <RangePicker defaultVisibleMonth={() => moment().add(-1, 'months')} onVisibleMonthChange={onVisibleMonthChange} />\n <br /><br />\n <p>Setting 2017 as default visible year</p>\n <MonthPicker defaultVisibleYear={() => moment('2017', 'YYYY')} />\n</div>, mountNode);
Setting default value by passing defaultValue
.
import { DatePicker } from '@alifd/next';\nimport moment from 'moment';\n\nconst { RangePicker, MonthPicker, YearPicker } = DatePicker;\nconst startValue = moment('2017-11-20', 'YYYY-MM-DD', true);\nconst endValue = moment('2017-12-15', 'YYYY-MM-DD', true);\nconst onChange = val => console.log(val);\n\nReactDOM.render(<div>\n <DatePicker defaultValue={startValue} onChange={onChange} /><br /><br />\n <MonthPicker defaultValue={startValue} onChange={onChange} /><br /><br />\n <YearPicker defaultValue={startValue} onChange={onChange} /><br /><br />\n <RangePicker defaultValue={[startValue, endValue]} onChange={onChange} />\n</div>, mountNode);
可以通过 defaultValue
属性为日期选择器提供初值,所提供的初值必须为 moment 对象。
import { DatePicker } from '@alifd/next';\nimport moment from 'moment';\n\nconst { RangePicker, MonthPicker, YearPicker } = DatePicker;\nconst startValue = moment('2017-11-20', 'YYYY-MM-DD', true);\nconst endValue = moment('2017-12-15', 'YYYY-MM-DD', true);\nconst onChange = val => console.log(val);\n\nReactDOM.render(<div>\n <DatePicker defaultValue={startValue} onChange={onChange} /><br /><br />\n <MonthPicker defaultValue={startValue} onChange={onChange} /><br /><br />\n <YearPicker defaultValue={startValue} onChange={onChange} /><br /><br />\n <RangePicker defaultValue={[startValue, endValue]} onChange={onChange} />\n</div>, mountNode);
Disable date cells by disabledDate
.
import { DatePicker } from '@alifd/next';\nimport moment from 'moment';\n\nconst { RangePicker, MonthPicker, YearPicker } = DatePicker;\nconst currentDate = moment();\n\n// Disable all dates before today\nconst disabledDate = function (date, view) {\n switch (view) {\n case 'date':\n return date.valueOf() <= currentDate.valueOf();\n case 'year':\n return date.year() < currentDate.year();\n case 'month':\n return date.year() * 100 + date.month() < currentDate.year() * 100 + currentDate.month();\n default: return false;\n }\n};\n\nReactDOM.render(<div>\n <DatePicker disabledDate={disabledDate} onChange={val => console.log(val)} /><br /><br />\n <MonthPicker disabledDate={disabledDate} onChange={val => console.log(val)} /><br /><br />\n <YearPicker disabledDate={disabledDate} onChange={val => console.log(val)} /><br /><br />\n <RangePicker disabledDate={disabledDate} onChange={val => console.log(val)} />\n</div>, mountNode);
可以通过 disabledDate
属性来禁止用户选择或输入某些特定日期。
import { DatePicker } from '@alifd/next';\nimport moment from 'moment';\n\nconst { RangePicker, MonthPicker, YearPicker } = DatePicker;\nconst currentDate = moment();\n\n// Disable all dates before today\nconst disabledDate = function (date, view) {\n switch (view) {\n case 'date':\n return date.valueOf() <= currentDate.valueOf();\n case 'year':\n return date.year() < currentDate.year();\n case 'month':\n return date.year() * 100 + date.month() < currentDate.year() * 100 + currentDate.month();\n default: return false;\n }\n};\n\nReactDOM.render(<div>\n <DatePicker disabledDate={disabledDate} onChange={val => console.log(val)} /><br /><br />\n <MonthPicker disabledDate={disabledDate} onChange={val => console.log(val)} /><br /><br />\n <YearPicker disabledDate={disabledDate} onChange={val => console.log(val)} /><br /><br />\n <RangePicker disabledDate={disabledDate} onChange={val => console.log(val)} />\n</div>, mountNode);
Disable the picker.
\n","order":"6"},"codes":{"jsx":"import { DatePicker } from '@alifd/next';\n\nconst { RangePicker } = DatePicker;\n\nReactDOM.render(import { DatePicker } from '@alifd/next';\n\nconst { RangePicker } = DatePicker;\n\nReactDOM.render(<div>\n <DatePicker disabled /> <RangePicker disabled />\n</div>, mountNode);
当开启 disabled
属性时,选择框处于完全禁用状态。
import { DatePicker } from '@alifd/next';\n\nconst { RangePicker } = DatePicker;\n\nReactDOM.render(<div>\n <DatePicker disabled /> <RangePicker disabled />\n</div>, mountNode);
Use case with Field.
\n","order":"12"},"codes":{"jsx":"import { DatePicker, Field, Button } from '@alifd/next';\n\nconst { RangePicker, YearPicker, MonthPicker } = DatePicker;\n\nclass App extends React.Component {\n\n field = new Field(this);\n\n printData = () => {\n this.field.validate((err, values) => {\n\n if (err) {\n console.error('Error: ', err);\n return;\n }\n\n console.log('datepicker: %s', values.date.format('YYYY-MM-DD'));\n console.log('monthpicker: %s', values.month.format('YYYY-MM'));\n console.log('yearpicker: %s', values.year.format('YYYY'));\n const range = values.range;\n console.log('rangepicker: [%s, %s]', range[0] && range[0].format('YYYY-MM-DD'), range[1] && range[1].format('YYYY-MM-DD'));\n });\n }\n\n printError = (name) => {\n if (this.field.getError(name)) {\n return {this.field.getError(name).join(',')};\n }\n }\n\n render() {\n const init = this.field.init;\n\n return (\nimport { DatePicker, Field, Button } from '@alifd/next';\n\nconst { RangePicker, YearPicker, MonthPicker } = DatePicker;\n\nclass App extends React.Component {\n\n field = new Field(this);\n\n printData = () => {\n this.field.validate((err, values) => {\n\n if (err) {\n console.error('Error: ', err);\n return;\n }\n\n console.log('datepicker: %s', values.date.format('YYYY-MM-DD'));\n console.log('monthpicker: %s', values.month.format('YYYY-MM'));\n console.log('yearpicker: %s', values.year.format('YYYY'));\n const range = values.range;\n console.log('rangepicker: [%s, %s]', range[0] && range[0].format('YYYY-MM-DD'), range[1] && range[1].format('YYYY-MM-DD'));\n });\n }\n\n printError = (name) => {\n if (this.field.getError(name)) {\n return <span className=\"error-msg\">{this.field.getError(name).join(',')}</span>;\n }\n }\n\n render() {\n const init = this.field.init;\n\n return (\n <div>\n <DatePicker {...init('date', { rules: [{\n required: true,\n message: '请选择日期'\n }] })} />{this.printError('date')}<br /><br />\n <MonthPicker {...init('month', { rules: [{\n required: true,\n message: '请选择月份'\n }] })} />{this.printError('month')}<br /><br />\n <YearPicker {...init('year', { rules: [{\n required: true,\n message: '请选择年份'\n }] })} />{this.printError('year')}<br /><br />\n <RangePicker {...init('range', { rules: [{\n required: true,\n message: '请选择日期范围'\n }] })} />{this.printError('range')}<br /><br />\n <Button onClick={this.printData}>Print to Console</Button>\n </div>\n );\n }\n}\n\nReactDOM.render(<App/>, mountNode);
.error-msg {\n color: #E72B00;\n font-size: 12px;\n}
与 Field 结合使用,简单示范自定义返回值
\n","order":"12"},"codes":{"jsx":"import { DatePicker, Field, Button } from '@alifd/next';\n\nconst { RangePicker, YearPicker, MonthPicker } = DatePicker;\n\nclass App extends React.Component {\n\n field = new Field(this);\n\n printData = () => {\n this.field.validate((err, values) => {\n\n if (err) {\n console.error('Error: ', err);\n return;\n }\n\n console.log('datepicker: %s', values.date.format('YYYY-MM-DD'));\n console.log('monthpicker: %s', values.month.format('YYYY-MM'));\n console.log('yearpicker: %s', values.year.format('YYYY'));\n const range = values.range;\n console.log('rangepicker: [%s, %s]', range[0] && range[0].format('YYYY-MM-DD'), range[1] && range[1].format('YYYY-MM-DD'));\n });\n }\n\n printError = (name) => {\n if (this.field.getError(name)) {\n return {this.field.getError(name).join(',')};\n }\n }\n\n render() {\n const init = this.field.init;\n\n return (\nimport { DatePicker, Field, Button } from '@alifd/next';\n\nconst { RangePicker, YearPicker, MonthPicker } = DatePicker;\n\nclass App extends React.Component {\n\n field = new Field(this);\n\n printData = () => {\n this.field.validate((err, values) => {\n\n if (err) {\n console.error('Error: ', err);\n return;\n }\n\n console.log('datepicker: %s', values.date.format('YYYY-MM-DD'));\n console.log('monthpicker: %s', values.month.format('YYYY-MM'));\n console.log('yearpicker: %s', values.year.format('YYYY'));\n const range = values.range;\n console.log('rangepicker: [%s, %s]', range[0] && range[0].format('YYYY-MM-DD'), range[1] && range[1].format('YYYY-MM-DD'));\n });\n }\n\n printError = (name) => {\n if (this.field.getError(name)) {\n return <span className=\"error-msg\">{this.field.getError(name).join(',')}</span>;\n }\n }\n\n render() {\n const init = this.field.init;\n\n return (\n <div>\n <DatePicker {...init('date', { rules: [{\n required: true,\n message: '请选择日期'\n }] })} />{this.printError('date')}<br /><br />\n <MonthPicker {...init('month', { rules: [{\n required: true,\n message: '请选择月份'\n }] })} />{this.printError('month')}<br /><br />\n <YearPicker {...init('year', { rules: [{\n required: true,\n message: '请选择年份'\n }] })} />{this.printError('year')}<br /><br />\n <RangePicker {...init('range', { rules: [{\n required: true,\n message: '请选择日期范围'\n }] })} />{this.printError('range')}<br /><br />\n <Button onClick={this.printData}>Print to Console</Button>\n </div>\n );\n }\n}\n\nReactDOM.render(<App/>, mountNode);
.error-msg {\n color: #E72B00;\n font-size: 12px;\n}
Passing custom footer with footerRender
.
import { DatePicker } from '@alifd/next';\n\nconst { RangePicker } = DatePicker;\n\nfunction footerRender() {\n return <div className=\"custom-footer\">👍 Some useful info here</div>;\n}\n\nReactDOM.render(<div>\n <DatePicker footerRender={footerRender} /> \n <RangePicker footerRender={footerRender} />\n</div>, mountNode);
.custom-footer {\n padding: 12px;\n font-size: 12px;\n border-top: 1px solid #DCDEE3;\n}
可以通过 footerRender
自定义对面板页脚的定制。
import { DatePicker } from '@alifd/next';\n\nconst { RangePicker } = DatePicker;\n\nfunction footerRender() {\n return <div className=\"custom-footer\">👍 Some useful info here</div>;\n}\n\nReactDOM.render(<div>\n <DatePicker footerRender={footerRender} /> \n <RangePicker footerRender={footerRender} />\n</div>, mountNode);
.custom-footer {\n padding: 12px;\n font-size: 12px;\n border-top: 1px solid #DCDEE3;\n}
Using attribute format
to change the displayed dates, it will be also used to check user inputs.
import { DatePicker } from '@alifd/next';\n\nconst { RangePicker } = DatePicker;\nconst onChange = val => console.log(val);\n\nReactDOM.render(<div>\n <DatePicker format=\"YYYY-M-D\" onChange={onChange} />\n <br /><br />\n <DatePicker format=\"YYYY-M-D\" onChange={onChange} showTime={{ format: 'HH:mm' }} />\n <br /><br />\n <RangePicker format=\"YYYY-M-D\" onChange={onChange} />\n <br /><br />\n <RangePicker format=\"YYYY-M-D\" onChange={onChange} showTime={{ format: 'HH:mm' }} />\n</div>, mountNode);
通过 format
属性可以约束日期选择器的日期格式,该格式同时会限定用户的输入格式。
import { DatePicker } from '@alifd/next';\n\nconst { RangePicker } = DatePicker;\nconst onChange = val => console.log(val);\n\nReactDOM.render(<div>\n <DatePicker format=\"YYYY-M-D\" onChange={onChange} />\n <br /><br />\n <DatePicker format=\"YYYY-M-D\" onChange={onChange} showTime={{ format: 'HH:mm' }} />\n <br /><br />\n <RangePicker format=\"YYYY-M-D\" onChange={onChange} />\n <br /><br />\n <RangePicker format=\"YYYY-M-D\" onChange={onChange} showTime={{ format: 'HH:mm' }} />\n</div>, mountNode);
Custom popup behaviors.
\n","order":"10"},"codes":{"jsx":"import { DatePicker } from '@alifd/next';\n\nconst { RangePicker } = DatePicker;\n\nReactDOM.render(Change popup align
\nChange popup container
\nChange popup align
\nChange popup container
\nimport { DatePicker } from '@alifd/next';\n\nconst { RangePicker } = DatePicker;\n\nReactDOM.render(<div>\n <p>Change popup align</p>\n <DatePicker popupAlign=\"bl tl\" />\n <p>Change popup container</p>\n <RangePicker popupContainer={target => target.parentNode} />\n</div>, mountNode);
组件对外透出了 visible
, defaultVisible
, onVisibleChange
, popupTriggerType
, popupAlign
, popupContainer
, popupStyle
, popupClassName
等属性用于直接定制弹层。此外,如果这些属性仍然无法满足需求,可以通过 popupProps
进行透传。
Change popup align
\nChange popup container
\nChange popup align
\nChange popup container
\nimport { DatePicker } from '@alifd/next';\n\nconst { RangePicker } = DatePicker;\n\nReactDOM.render(<div>\n <p>Change popup align</p>\n <DatePicker popupAlign=\"bl tl\" />\n <p>Change popup container</p>\n <RangePicker popupContainer={target => target.parentNode} />\n</div>, mountNode);
Enable showTime
to create a DatePicker/RangePicker with time.
DatePicker With Time
\nDatePicker with Time, reset 00:00:00 for every select
\nDatePicker with Time, with default time value
\nRangePicker with Time
\nRangePicker with Time, reset 00:00:00 for every select
\nRangePicker with Time, with default time value, hide seconds
\nRangePicker with Time, with default start & end time value, hide seconds
\nDatePicker With Time
\nDatePicker with Time, reset 00:00:00 for every select
\nDatePicker with Time, with default time value
\nRangePicker with Time
\nRangePicker with Time, reset 00:00:00 for every select
\nRangePicker with Time, with default time value, hide seconds
\nRangePicker with Time, with default start & end time value, hide seconds
\nimport { DatePicker } from '@alifd/next';\nimport moment from 'moment';\n\nconst { RangePicker } = DatePicker;\nconst onChange = (value) => console.log(value);\nconst onOk = (value) => console.log('onOK:', value.format('YYYY-MM-DD HH:mm:ss'));\nconst onRangeOk = (value) => console.log('onOk: [%s, %s]', value[0].format('YYYY-MM-DD HH:mm:ss'), value[1].format('YYYY-MM-DD HH:mm:ss'));\n\nconst defaultTimeValue = moment('09:00:00', 'HH:mm:ss', true);\nconst defaultTimeValues = [moment('09:00:00', 'HH:mm:ss', true), moment('23:59:59', 'HH:mm:ss', true)];\n\nReactDOM.render(<div>\n <p>DatePicker With Time</p>\n <DatePicker showTime onChange={onChange} onOk={onOk} />\n <p>DatePicker with Time, reset 00:00:00 for every select</p>\n <DatePicker showTime onChange={onChange} onOk={onOk} resetTime />\n <p>DatePicker with Time, with default time value</p>\n <DatePicker showTime={{ defaultValue: defaultTimeValue, secondStep: 10 }} onChange={onChange} onOk={onOk} />\n <p>RangePicker with Time</p>\n <RangePicker showTime onChange={onChange} onOk={onRangeOk} />\n <p>RangePicker with Time, reset 00:00:00 for every select</p>\n <RangePicker showTime resetTime onChange={onChange} onOk={onRangeOk} />\n <p>RangePicker with Time, with default time value, hide seconds</p>\n <RangePicker showTime={{ defaultValue: defaultTimeValue, format: 'HH:mm', minuteStep: 15 }} onChange={onChange} onOk={onRangeOk} />\n <p>RangePicker with Time, with default start & end time value, hide seconds</p>\n <RangePicker showTime={{ defaultValue: defaultTimeValues, format: 'HH:mm', minuteStep: 15 }} onChange={onChange} onOk={onRangeOk} />\n</div>, mountNode);
如果需要同时选择时间,可以通过 showTime
属性开启,showTime
支持传入 TimePickerPanel 的属性,例如 format
, defaultValue
等。
DatePicker With Time
\nDatePicker with Time, reset 00:00:00 for every select
\nDatePicker with Time, with default time value
\nRangePicker with Time
\nRangePicker with Time, reset 00:00:00 for every select
\nRangePicker with Time, with default time value, hide seconds
\nRangePicker with Time, with default start & end time value, hide seconds
\nDatePicker With Time
\nDatePicker with Time, reset 00:00:00 for every select
\nDatePicker with Time, with default time value
\nRangePicker with Time
\nRangePicker with Time, reset 00:00:00 for every select
\nRangePicker with Time, with default time value, hide seconds
\nRangePicker with Time, with default start & end time value, hide seconds
\nimport { DatePicker } from '@alifd/next';\nimport moment from 'moment';\n\nconst { RangePicker } = DatePicker;\nconst onChange = (value) => console.log(value);\nconst onOk = (value) => console.log('onOK:', value.format('YYYY-MM-DD HH:mm:ss'));\nconst onRangeOk = (value) => console.log('onOk: [%s, %s]', value[0].format('YYYY-MM-DD HH:mm:ss'), value[1].format('YYYY-MM-DD HH:mm:ss'));\n\nconst defaultTimeValue = moment('09:00:00', 'HH:mm:ss', true);\nconst defaultTimeValues = [moment('09:00:00', 'HH:mm:ss', true), moment('23:59:59', 'HH:mm:ss', true)];\n\nReactDOM.render(<div>\n <p>DatePicker With Time</p>\n <DatePicker showTime onChange={onChange} onOk={onOk} />\n <p>DatePicker with Time, reset 00:00:00 for every select</p>\n <DatePicker showTime onChange={onChange} onOk={onOk} resetTime />\n <p>DatePicker with Time, with default time value</p>\n <DatePicker showTime={{ defaultValue: defaultTimeValue, secondStep: 10 }} onChange={onChange} onOk={onOk} />\n <p>RangePicker with Time</p>\n <RangePicker showTime onChange={onChange} onOk={onRangeOk} />\n <p>RangePicker with Time, reset 00:00:00 for every select</p>\n <RangePicker showTime resetTime onChange={onChange} onOk={onRangeOk} />\n <p>RangePicker with Time, with default time value, hide seconds</p>\n <RangePicker showTime={{ defaultValue: defaultTimeValue, format: 'HH:mm', minuteStep: 15 }} onChange={onChange} onOk={onRangeOk} />\n <p>RangePicker with Time, with default start & end time value, hide seconds</p>\n <RangePicker showTime={{ defaultValue: defaultTimeValues, format: 'HH:mm', minuteStep: 15 }} onChange={onChange} onOk={onRangeOk} />\n</div>, mountNode);
Change size by attribute size
.
import { DatePicker } from '@alifd/next';\n\nReactDOM.render(<div>\n <DatePicker size=\"large\" /> \n <DatePicker /> \n <DatePicker size=\"small\" />\n</div>, mountNode);
通过 size
属性可以改变 Input 组件的尺寸,默认为 medium
。
import { DatePicker } from '@alifd/next';\n\nReactDOM.render(<div>\n <DatePicker size=\"large\" /> \n <DatePicker /> \n <DatePicker size=\"small\" />\n</div>, mountNode);
DatePicker are used to select a single date for an input.
\nParam | \nDescripiton | \nType | \nDefault Value | \n
---|---|---|---|
label | \nInset label of input | \nReactNode | \n- | \n
size | \nSize of input option: 'small', 'medium', 'large' | \nEnum | \n'medium' | \n
state | \nState of input option: 'success', 'error' | \nEnum | \n- | \n
placeholder | \nPlaceholder of input | \nString | \n- | \n
defaultVisibleMonth | \nDefault visible month signature: Function() => MomentObject return: {MomentObject} moment instance with specified month | \nFunction | \n- | \n
value | \nValue of date-picker | \ncustom | \n- | \n
defaultValue | \nDefault value of date-picker | \ncustom | \n- | \n
format | \nFormat of date value (it will also effect user input) | \nString | \n'YYYY-MM-DD' | \n
showTime | \nEnable time-picker, pass object like { defaultValue, format, ... } | \nObject/Boolean | \nfalse | \n
resetTime | \nIf reset time for every re-select | \nBoolean | \nfalse | \n
disabledDate | \nFunction to disable date signature: Function(dateValue: MomentObject) => Boolean parameter: dateValue: {MomentObject} null view: {Enum} current view type: 'year', 'month', 'date' return: {Boolean} if disable current date | \nFunction | \n() => false | \n
footerRender | \nTemplate render for custom footer signature: Function() => Node return: {Node} Custom footer | \nFunction | \n() => null | \n
onChange | \nCallback when date changes signature: Function() => MomentObject return: {MomentObject} dateValue | \nFunction | \nfunc.noop | \n
onOk | \nCallback when click the ok button signature: Function() => MomentObject return: {MomentObject} dateValue | \nFunction | \nfunc.noop | \n
disabled | \nDisable the picker | \nBoolean | \n- | \n
hasClear | \nHas clear icon | \nBoolean | \ntrue | \n
visible | \nVisible state of popup | \nBoolean | \n- | \n
defaultVisible | \nDefault visible state of popup | \nBoolean | \n- | \n
onVisibleChange | \nCallback when visible state changes signature: Function(visible: Boolean, reason: String) => void parameter: visible: {Boolean} if popup visible reason: {String} reason to change visible | \nFunction | \nfunc.noop | \n
popupTriggerType | \nTrigger type of popup option: 'click', 'hover' | \nEnum | \n'click' | \n
popupAlign | \nAlign of popup, see Overlay doc for detail | \nString | \n'tl tl' | \n
popupContainer | \nContainer of popup signature: Function(target: Element) => Element parameter: target: {Element} target element return: {Element} container of popup | \nFunction | \n- | \n
popupStyle | \nCustom style of popup | \nObject | \n- | \n
popupClassName | \nCustom className of popup | \nString | \n- | \n
popupProps | \nProps of popup | \nObject | \n- | \n
followTrigger | \nfollow Trigger or not | \nBoolean | \n- | \n
dateInputAriaLabel | \nDate input aria-label attr | \nString | \n- | \n
Param | \nDescription | \nType | \nDefault Value | \n||
---|---|---|---|---|---|
size | \nSize of input option: 'small', 'medium', 'large' | \nEnum | \n'medium' | \n||
defaultVisibleMonth | \nDefault visible month signature: Function() => MomentObject return: {MomentObject} moment instance with specified month | \nFunction | \n- | \n||
value | \nRange value [moment, moment] | \nArray | \n- | \n||
defaultValue | \nDefault range value [moment, moment] | \nArray | \n- | \n||
format | \nDate format | \nString | \n'YYYY-MM-DD' | \n||
showTime | \nEnable time picker | \nObject/Boolean | \nfalse | \n||
resetTime | \nIf reset time for every select | \nBoolean | \nfalse | \n||
disabledDate | \nFunction to disable dates signature: Function(dateValue: MomentObject) => Boolean parameter: dateValue: {MomentObject} null view: {Enum} current view type: 'year', 'month', 'date' return: {Boolean} if disabled | \nFunction | \n() => false | \n||
footerRender | \nTemplate render for footer signature: Function() => Node return: {Node} custom footer | \nFunction | \n() => null | \n||
onChange | \nCallback when date changes signature: Function() => MomentObject return: {MomentObject} range values | \nFunction | \nfunc.noop | \n||
onOk | \nCallback when click ok button signature: Function() => MomentObject return: {MomentObject} range values | \nFunction | \nfunc.noop | \n||
label | \nInset label of input | \nReactNode | \n- | \n||
state | \nState of input option: 'error', 'success' | \nEnum | \n- | \n||
disabled | \nDisable the picker | \nBoolean | \n- | \n||
hasClear | \nHas clear icon | \nBoolean | \ntrue | \n||
visible | \nVisible state of popup | \nBoolean | \n- | \n||
defaultVisible | \nDefault visible state of popup | \nBoolean | \n- | \n||
onVisibleChange | \nCallback when visible state changes signature: Function(visible: Boolean, reason: String) => void parameter: visible: {Boolean} if popup visible reason: {String} reason to change visible | \nFunction | \nfunc.noop | \n||
popupTriggerType | \nTrigger type of popup option: 'click', 'hover' | \nEnum | \n'click' | \n||
popupAlign | \nAlign of popup | \nString | \n'tl tl' | \n||
popupContainer | \nContainer of a popup signature: Function(target: Element) => Element option: target: {Element} target element return: {Element} coninter element of popup | \nFunction | \n- | \n||
popupStyle | \nCustom style of popup | \nObject | \n- | \n||
popupClassName | \nCustom className of popup | \nString | \n- | \n||
popupProps | \nProps of popup | \nObject | \n- | \n||
startDateInputAriaLabel | \nStart date input aria-label attribute | \nString | \n- | \n\n | \n |
startTimeInputAriaLabel | \nStart time input aria-label attribute | \nString | \n- | \n\n | \n |
endDateInputAriaLabel | \nEnd date input aria-label attribute | \nString | \n- | \n\n | \n |
endTimeInputAriaLabel | \nEnd time input aria-label attribute | \nString | \n- | \n\n |
When the Date Picker
is focused, press enter
will open popup to input date or time.
按键 | \n说明 | \n
---|---|
number key | \nNeed to manual input the date, the specified date format | \n
Enter | \nopen the calendar or select date after input date | \n
Esc | \nclose the calendar | \n
Up | \nInput previous day(Month Picker is previous month, Year Picker is previous year) | \n
Down | \nInput next day(Month Picker is next month, Year Picker is next year) | \n
Page Up | \nInput previous month | \n
Page Down | \nInput next month | \n
Alt + Page Up | \nInput previous year | \n
Alt + Page Down | \nInput next year | \n
输入或选择日期的控件。当用户需要输入一个日期,可以点击标准输入框,弹出日期面板进行选择。
\nDatePicker/RangePicker 在交互上增加了操作焦点的设置,意味着,如果某个输入框处于 focus 态,那么当前选择的日期将会作用于该输入框对应的日期。
\n如上图所示,带时间的 RangePicker 有 4 个输入焦点,分别为开始日期、开始时间、结束日期、结束时间。当用户激活某个输入框时,此时下拉选择的日期将会作用域该输入框。同时设置了如下两个规则:
\n由于 Calendar 组件内部使用 moment 对象来设置日期(请使用最新版 moment),部分 Locale 读取自 moment,因此用户需要在外部使用时正确的设置 moment 的 locale 。
\nimport moment from 'moment';\n\nmoment.locale('zh-cn');
此外,当改变 moment 的全局 locale 时并不会修改之前的已有实例,例如:
\nmoment.locale('fr');\nconst m = moment(1316116057189);\nm.fromNow(); // il y a une heure\n\nmoment.locale('en');\nm.fromNow(); // il y a une heure\nmoment(1316116057189).fromNow(); // an hour ago
除了全局设置 moment 的多语言,还可以只对某个 moment 实例设置多语言。比如:
\nconst value = moment();\nvalue.locale('fr'); // set this instance to use French
DatePicker 默认情况下接收和返回的数据类型都是 Moment 对象。为了便于用户的使用,DatePikcer 还支持直接传入字符串(组件内部仍然会格式化为 Moment 对象)。使用方法如下:
\n标准非受控
\n<DatePicker onChange={val => console.log(val)} />\n// select 2019-01-23\n// >> MomentObject\n\n<DatePicker defaultValue={moment()} onChange={val => console.log(val)} />\n// select 2019-01-23\n// >> MomentObject\n\n<DatePicker defaultValue="2018-01-23" onChange={val => console.log(val)} />\n// select 2019-01-23\n// >> "2019-01-23"
标准受控
\n<DatePicker value={moment()} onChange={val => console.log(val)} />\n// setProps({ value: moment().add(1, 'months') })\n// >> MomentObject\n\n<DatePicker value="2018-01-23" onChange={val => console.log(val)} />\n// setProps({ value: '2019-01-23' })\n// >> "2019-01-23"
参数 | \n说明 | \n类型 | \n默认值 | \n
---|---|---|---|
label | \n输入框内置标签 | \nReactNode | \n- | \n
size | \n输入框尺寸 可选值: 'small', 'medium', 'large' | \nEnum | \n'medium' | \n
state | \n输入框状态 可选值: 'success', 'loading', 'error' | \nEnum | \n- | \n
placeholder | \n输入提示 | \nString | \n- | \n
defaultVisibleMonth | \n默认展现的月 签名: Function() => MomentObject 返回值: {MomentObject} 返回包含指定月份的 moment 对象实例 | \nFunction | \n- | \n
value | \n日期值(受控)moment 对象 | \ncustom | \n- | \n
defaultValue | \n初始日期值,moment 对象 | \ncustom | \n- | \n
format | \n日期值的格式(用于限定用户输入和展示) | \nString | \n'YYYY-MM-DD' | \n
showTime | \n是否使用时间控件,传入 TimePicker 的属性 { defaultValue, format, ... } | \nObject/Boolean | \nfalse | \n
resetTime | \n每次选择日期时是否重置时间(仅在 showTime 开启时有效) | \nBoolean | \nfalse | \n
disabledDate | \n禁用日期函数 签名: Function(日期值: MomentObject, view: String) => Boolean 参数: 日期值: {MomentObject} null view: {String} 当前视图类型,year: 年, month: 月, date: 日 返回值: {Boolean} 是否禁用 | \nFunction | \n() => false | \n
footerRender | \n自定义面板页脚 签名: Function() => Node 返回值: {Node} 自定义的面板页脚组件 | \nFunction | \n() => null | \n
onChange | \n日期值改变时的回调 签名: Function(value: MomentObject/String) => void 参数: value: {MomentObject/String} 日期值 | \nFunction | \nfunc.noop | \n
onOk | \n点击确认按钮时的回调 签名: Function() => MomentObject/String 返回值: {MomentObject/String} 日期值 | \nFunction | \nfunc.noop | \n
disabled | \n是否禁用 | \nBoolean | \n- | \n
hasClear | \n是否显示清空按钮 | \nBoolean | \ntrue | \n
visible | \n弹层显示状态 | \nBoolean | \n- | \n
defaultVisible | \n弹层默认是否显示 | \nBoolean | \nfalse | \n
onVisibleChange | \n弹层展示状态变化时的回调 签名: Function(visible: Boolean, type: String) => void 参数: visible: {Boolean} 弹层是否显示 type: {String} 触发弹层显示和隐藏的来源 calendarSelect 表示由日期表盘的选择触发; okBtnClick 表示由确认按钮触发; fromTrigger 表示由trigger的点击触发; docClick 表示由document的点击触发 | \nFunction | \nfunc.noop | \n
popupTriggerType | \n弹层触发方式 可选值: 'click', 'hover' | \nEnum | \n'click' | \n
popupAlign | \n弹层对齐方式,具体含义见 OverLay文档 | \nString | \n'tl tl' | \n
popupContainer | \n弹层容器 签名: Function(target: Element) => Element 参数: target: {Element} 目标元素 返回值: {Element} 弹层的容器元素 | \nFunction | \n- | \n
popupStyle | \n弹层自定义样式 | \nObject | \n- | \n
popupClassName | \n弹层自定义样式类 | \nString | \n- | \n
popupProps | \n弹层其他属性 | \nObject | \n- | \n
followTrigger | \n是否跟随滚动 | \nBoolean | \n- | \n
inputProps | \n输入框其他属性 | \nObject | \n- | \n
dateCellRender | \n自定义日期渲染函数 签名: Function(value: Object) => ReactNode 参数: value: {Object} 日期值(moment对象) 返回值: {ReactNode} null | \nFunction | \n- | \n
monthCellRender | \n自定义月份渲染函数 签名: Function(calendarDate: Object) => ReactNode 参数: calendarDate: {Object} 对应 Calendar 返回的自定义日期对象 返回值: {ReactNode} null | \nFunction | \n- | \n
dateInputAriaLabel | \n日期输入框的 aria-label 属性 | \nString | \n- | \n
timeInputAriaLabel | \n时间输入框的 aria-label 属性 | \nString | \n- | \n
参数 | \n说明 | \n类型 | \n默认值 | \n
---|---|---|---|
label | \n输入框内置标签 | \nReactNode | \n- | \n
size | \n输入框尺寸 可选值: 'small', 'medium', 'large' | \nEnum | \n'medium' | \n
state | \n输入框状态 可选值: 'success', 'loading', 'error' | \nEnum | \n- | \n
placeholder | \n输入提示 | \nString | \n- | \n
defaultVisibleYear | \n默认展现的年 签名: Function() => MomentObject 返回值: {MomentObject} 返回包含指定年份的 moment 对象实例 | \nFunction | \n- | \n
value | \n日期值(受控)moment 对象 | \ncustom | \n- | \n
defaultValue | \n初始日期值,moment 对象 | \ncustom | \n- | \n
format | \n日期值的格式(用于限定用户输入和展示) | \nString | \n'YYYY-MM' | \n
disabledDate | \n禁用日期函数 签名: Function(日期值: MomentObject, view: String) => Boolean 参数: 日期值: {MomentObject} null view: {String} 当前视图类型,year: 年, month: 月, date: 日 返回值: {Boolean} 是否禁用 | \nFunction | \n() => false | \n
footerRender | \n自定义面板页脚 签名: Function() => Node 返回值: {Node} 自定义的面板页脚组件 | \nFunction | \n() => null | \n
onChange | \n日期值改变时的回调 签名: Function(value: MomentObject/String) => void 参数: value: {MomentObject/String} 日期值 | \nFunction | \nfunc.noop | \n
disabled | \n是否禁用 | \nBoolean | \n- | \n
hasClear | \n是否显示清空按钮 | \nBoolean | \ntrue | \n
visible | \n弹层显示状态 | \nBoolean | \n- | \n
defaultVisible | \n弹层默认是否显示 | \nBoolean | \n- | \n
onVisibleChange | \n弹层展示状态变化时的回调 签名: Function(visible: Boolean, type: String) => void 参数: visible: {Boolean} 弹层是否显示 type: {String} 触发弹层显示和隐藏的来源 calendarSelect 表示由日期表盘的选择触发; fromTrigger 表示由trigger的点击触发; docClick 表示由document的点击触发 | \nFunction | \nfunc.noop | \n
popupTriggerType | \n弹层触发方式 可选值: 'click', 'hover' | \nEnum | \n'click' | \n
popupAlign | \n弹层对齐方式, 具体含义见 OverLay文档 | \nString | \n'tl tl' | \n
popupContainer | \n弹层容器 签名: Function(target: Element) => Element 参数: target: {Element} 目标元素 返回值: {Element} 弹层的容器元素 | \nFunction | \n- | \n
popupStyle | \n弹层自定义样式 | \nObject | \n- | \n
popupClassName | \n弹层自定义样式类 | \nString | \n- | \n
popupProps | \n弹层其他属性 | \nObject | \n- | \n
followTrigger | \n是否跟随滚动 | \nBoolean | \n- | \n
inputProps | \n输入框其他属性 | \nObject | \n- | \n
monthCellRender | \n自定义月份渲染函数 签名: Function(calendarDate: Object) => ReactNode 参数: calendarDate: {Object} 对应 Calendar 返回的自定义日期对象 返回值: {ReactNode} null | \nFunction | \n- | \n
dateInputAriaLabel | \n日期输入框的 aria-label 属性 | \nString | \n- | \n
参数 | \n说明 | \n类型 | \n默认值 | \n\n | \n | ||
---|---|---|---|---|---|---|---|
defaultVisibleMonth | \n默认展示的起始月份 签名: Function() => MomentObject 返回值: {MomentObject} 返回包含指定月份的 moment 对象实例 | \nFunction | \n- | \n\n | \n | ||
size | \n输入框尺寸 可选值: 'small', 'medium', 'large' | \nEnum | \n'medium' | \n\n | \n | ||
value | \n日期范围值数组 [moment, moment] | \nArray | \n- | \n\n | \n | ||
defaultValue | \n初始的日期范围值数组 [moment, moment] | \nArray | \n- | \n\n | \n | ||
format | \n日期格式 | \nString | \n'YYYY-MM-DD' | \n\n | \n | ||
showTime | \n是否使用时间控件,支持传入 TimePicker 的属性 | \nObject/Boolean | \nfalse | \n\n | \n | ||
resetTime | \n每次选择是否重置时间(仅在 showTime 开启时有效) | \nBoolean | \nfalse | \n\n | \n | ||
disabledDate | \n禁用日期函数 签名: Function(日期值: MomentObject, view: String) => Boolean 参数: 日期值: {MomentObject} null view: {String} 当前视图类型,year: 年, month: 月, date: 日 返回值: {Boolean} 是否禁用 | \nFunction | \n() => false | \n\n | \n | ||
footerRender | \n自定义面板页脚 签名: Function() => Node 返回值: {Node} 自定义的面板页脚组件 | \nFunction | \n() => null | \n\n | \n | ||
onChange | \n日期范围值改变时的回调 [ MomentObject | \nString, MomentObject | \nString ] 签名: Function(value: Array) => void 参数: value: {Array} 日期值 | \nFunction | \nfunc.noop | \n||
onOk | \n点击确认按钮时的回调 返回开始时间和结束时间`[ MomentObject | \nString, MomentObject | \nString ]` 签名: Function() => Array 返回值: {Array} 日期范围 | \nFunction | \nfunc.noop | \n\n | \n |
label | \n输入框内置标签 | \nReactNode | \n- | \n\n | \n | ||
state | \n输入框状态 可选值: 'error', 'loading', 'success' | \nEnum | \n- | \n\n | \n | ||
disabled | \n是否禁用 | \nBoolean | \n- | \n\n | \n | ||
hasClear | \n是否显示清空按钮 | \nBoolean | \ntrue | \n\n | \n | ||
visible | \n弹层显示状态 | \nBoolean | \n- | \n\n | \n | ||
defaultVisible | \n弹层默认是否显示 | \nBoolean | \nfalse | \n\n | \n | ||
onVisibleChange | \n弹层展示状态变化时的回调 签名: Function(visible: Boolean, type: String) => void 参数: visible: {Boolean} 弹层是否显示 type: {String} 触发弹层显示和隐藏的来源 okBtnClick 表示由确认按钮触发; fromTrigger 表示由trigger的点击触发; docClick 表示由document的点击触发 | \nFunction | \nfunc.noop | \n\n | \n | ||
popupTriggerType | \n弹层触发方式 可选值: 'click', 'hover' | \nEnum | \n'click' | \n\n | \n | ||
popupAlign | \n弹层对齐方式, 具体含义见 OverLay文档 | \nString | \n'tl tl' | \n\n | \n | ||
popupContainer | \n弹层容器 签名: Function(target: Element) => Element 参数: target: {Element} 目标元素 返回值: {Element} 弹层的容器元素 | \nFunction | \n- | \n\n | \n | ||
popupStyle | \n弹层自定义样式 | \nObject | \n- | \n\n | \n | ||
popupClassName | \n弹层自定义样式类 | \nString | \n- | \n\n | \n | ||
popupProps | \n弹层其他属性 | \nObject | \n- | \n\n | \n | ||
followTrigger | \n是否跟随滚动 | \nBoolean | \n- | \n\n | \n | ||
inputProps | \n输入框其他属性 | \nObject | \n- | \n\n | \n | ||
dateCellRender | \n自定义日期单元格渲染 签名: Function() => void | \nFunction | \n- | \n\n | \n | ||
monthCellRender | \n自定义月份渲染函数 签名: Function(calendarDate: Object) => ReactNode 参数: calendarDate: {Object} 对应 Calendar 返回的自定义日期对象 返回值: {ReactNode} null | \nFunction | \n- | \n\n | \n | ||
startDateInputAriaLabel | \n开始日期输入框的 aria-label 属性 | \nString | \n- | \n\n | \n | ||
startTimeInputAriaLabel | \n开始时间输入框的 aria-label 属性 | \nString | \n- | \n\n | \n | ||
endDateInputAriaLabel | \n结束日期输入框的 aria-label 属性 | \nString | \n- | \n\n | \n | ||
endTimeInputAriaLabel | \n结束时间输入框的 aria-label 属性 | \nString | \n- | \n\n |
参数 | \n说明 | \n类型 | \n默认值 | \n
---|---|---|---|
label | \n输入框内置标签 | \nReactNode | \n- | \n
size | \n输入框尺寸 可选值: 'small', 'medium', 'large' | \nEnum | \n'medium' | \n
state | \n输入框状态 可选值: 'success', 'loading', 'error' | \nEnum | \n- | \n
placeholder | \n输入提示 | \nString | \n- | \n
value | \n日期值(受控)moment 对象 | \ncustom | \n- | \n
defaultValue | \n初始日期值,moment 对象 | \ncustom | \n- | \n
format | \n日期值的格式(用于限定用户输入和展示) | \nString | \n'YYYY' | \n
disabledDate | \n禁用日期函数 签名: Function(日期值: MomentObject, view: String) => Boolean 参数: 日期值: {MomentObject} null view: {String} 当前视图类型,year: 年, month: 月, date: 日 返回值: {Boolean} 是否禁用 | \nFunction | \n() => false | \n
footerRender | \n自定义面板页脚 签名: Function() => Node 返回值: {Node} 自定义的面板页脚组件 | \nFunction | \n() => null | \n
onChange | \n日期值改变时的回调 签名: Function(value: MomentObject/String) => void 参数: value: {MomentObject/String} 日期值 | \nFunction | \nfunc.noop | \n
disabled | \n是否禁用 | \nBoolean | \n- | \n
hasClear | \n是否显示清空按钮 | \nBoolean | \ntrue | \n
visible | \n弹层显示状态 | \nBoolean | \n- | \n
defaultVisible | \n弹层默认是否显示 | \nBoolean | \n- | \n
onVisibleChange | \n弹层展示状态变化时的回调 签名: Function(visible: Boolean, reason: String) => void 参数: visible: {Boolean} 弹层是否显示 reason: {String} 触发弹层显示和隐藏的来源 calendarSelect 表示由日期表盘的选择触发; fromTrigger 表示由trigger的点击触发; docClick 表示由document的点击触发 | \nFunction | \nfunc.noop | \n
popupTriggerType | \n弹层触发方式 可选值: 'click', 'hover' | \nEnum | \n'click' | \n
popupAlign | \n弹层对齐方式, 具体含义见 OverLay文档 | \nString | \n'tl tl' | \n
popupContainer | \n弹层容器 签名: Function(target: Element) => Element 参数: target: {Element} 目标元素 返回值: {Element} 弹层的容器元素 | \nFunction | \n- | \n
popupStyle | \n弹层自定义样式 | \nObject | \n- | \n
popupClassName | \n弹层自定义样式类 | \nString | \n- | \n
popupProps | \n弹层其他属性 | \nObject | \n- | \n
followTrigger | \n是否跟随滚动 | \nBoolean | \n- | \n
inputProps | \n输入框其他属性 | \nObject | \n- | \n
dateInputAriaLabel | \n日期输入框的 aria-label 属性 | \nString | \n- | \n
同选择框一样聚焦到 DatePiker 后,需要按下 ENTER
键打开弹出框,选择/输入日期, 通过 TAB
切换日期和时间输入框。
按键 | \n说明 | \n
---|---|
数字键 | \n需要手动输入日期,指定的日期格式 | \n
Enter | \n打开日期选择框或输入后选择日期 | \n
Esc | \n关闭日期选择框 | \n
Up | \n输入上一天(Month Picker 则是上一个月, Year Picker 则是上一年) | \n
Down | \n输入下一天(Month Picker 则是下一个月, Year Picker 则是下一年) | \n
Page Up | \n输入上一月 | \n
Page Down | \n输入下一月 | \n
Alt + Page Up | \n输入上一年 | \n
Alt + Page Down | \n输入下一年 | \n
Set the aria-label
attribute via okProps
and cancelProps
, The screen reader will read the OK and Cancel buttons. Please refer to ARIA and KeyBoard
for keyboard operation.
\nimport { Button, Dialog } from '@alifd/next';\n\nclass Demo extends React.Component {\n state = {\n visible: false\n };\n onOpen = () => {\n this.setState({\n visible: true\n });\n };\n onClose = () => {\n this.setState({\n visible: false\n });\n };\n render() {\n return (\n <div>\n <Button onClick={this.onOpen} type=\"primary\">\n Open dialog\n </Button>\n <Dialog\n title=\"Welcome to Alibaba.com\"\n visible={this.state.visible}\n autoFocus\n onOk={this.onClose.bind(this, 'okClick')}\n onCancel={this.onClose.bind(this, 'cancelClick')}\n onClose={this.onClose}\n cancelProps={{'aria-label':'cancel'}}\n okProps={{'aria-label':'ok'}}>\n <p tabIndex=\"0\"> Start your business here by searching a popular product</p>\n </Dialog>\n </div>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);\n
通过okProps
与cancelProps
设置aria-label
属性,屏幕阅读器读取确定和取消按钮。关于键盘操作请参考ARIA and KeyBoard
。
\nimport { Button, Dialog } from '@alifd/next';\n\nclass Demo extends React.Component {\n state = {\n visible: false\n };\n onOpen = () => {\n this.setState({\n visible: true\n });\n };\n onClose = () => {\n this.setState({\n visible: false\n });\n };\n render() {\n return (\n <div>\n <Button onClick={this.onOpen} type=\"primary\">\n Open dialog\n </Button>\n <Dialog\n title=\"Welcome to Alibaba.com\"\n visible={this.state.visible}\n autoFocus\n onOk={this.onClose.bind(this, 'okClick')}\n onCancel={this.onClose.bind(this, 'cancelClick')}\n onClose={this.onClose}\n cancelProps={{'aria-label':'cancel'}}\n okProps={{'aria-label':'ok'}}>\n <p tabIndex=\"0\"> Start your business here by searching a popular product</p>\n </Dialog>\n </div>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);\n
First dialog
\n","order":"0"},"codes":{"jsx":"import { Button, Dialog } from '@alifd/next';\n\n\nclass Demo extends React.Component {\n state = {\n visible: false\n };\n\n onOpen = () => {\n this.setState({\n visible: true\n });\n };\n\n onClose = reason => {\n console.log(reason);\n\n this.setState({\n visible: false\n });\n };\n\n render() {\n return (\nimport { Button, Dialog } from '@alifd/next';\n\n\nclass Demo extends React.Component {\n state = {\n visible: false\n };\n\n onOpen = () => {\n this.setState({\n visible: true\n });\n };\n\n onClose = reason => {\n console.log(reason);\n\n this.setState({\n visible: false\n });\n };\n\n render() {\n return (\n <div>\n <Button onClick={this.onOpen} type=\"primary\">\n Open dialog\n </Button>\n <Dialog\n title=\"Welcome to Alibaba.com\"\n visible={this.state.visible}\n onOk={this.onClose.bind(this, 'okClick')}\n onCancel={this.onClose.bind(this, 'cancelClick')}\n onClose={this.onClose}>\n Start your business here by searching a popular product\n </Dialog>\n </div>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
第一个对话框
\n","order":"0"},"codes":{"jsx":"import { Button, Dialog } from '@alifd/next';\n\n\nclass Demo extends React.Component {\n state = {\n visible: false\n };\n\n onOpen = () => {\n this.setState({\n visible: true\n });\n };\n\n onClose = reason => {\n console.log(reason);\n\n this.setState({\n visible: false\n });\n };\n\n render() {\n return (\nimport { Button, Dialog } from '@alifd/next';\n\n\nclass Demo extends React.Component {\n state = {\n visible: false\n };\n\n onOpen = () => {\n this.setState({\n visible: true\n });\n };\n\n onClose = reason => {\n console.log(reason);\n\n this.setState({\n visible: false\n });\n };\n\n render() {\n return (\n <div>\n <Button onClick={this.onOpen} type=\"primary\">\n Open dialog\n </Button>\n <Dialog\n title=\"Welcome to Alibaba.com\"\n visible={this.state.visible}\n onOk={this.onClose.bind(this, 'okClick')}\n onCancel={this.onClose.bind(this, 'cancelClick')}\n onClose={this.onClose}>\n Start your business here by searching a popular product\n </Dialog>\n </div>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
The default footer is ok and cancel buttons, you can customize footer content.
\n","order":"2"},"codes":{"jsx":"import { Button, Dialog } from '@alifd/next';\n\n\nclass Demo extends React.Component {\n state = {\n visible: false\n };\n\n onOpenFullyCustomized = () => {\n this.setState({\n fullyCustomizedVisible: true\n });\n };\n\n onCloseFullyCustomized = () => {\n this.setState({\n fullyCustomizedVisible: false\n });\n };\n\n onOpenTextCustomized = () => {\n this.setState({\n textCustomizedVisible: true\n });\n };\n\n onCloseTextCustomized = () => {\n this.setState({\n textCustomizedVisible: false\n });\n };\n\n render() {\n return (\nimport { Button, Dialog } from '@alifd/next';\n\n\nclass Demo extends React.Component {\n state = {\n visible: false\n };\n\n onOpenFullyCustomized = () => {\n this.setState({\n fullyCustomizedVisible: true\n });\n };\n\n onCloseFullyCustomized = () => {\n this.setState({\n fullyCustomizedVisible: false\n });\n };\n\n onOpenTextCustomized = () => {\n this.setState({\n textCustomizedVisible: true\n });\n };\n\n onCloseTextCustomized = () => {\n this.setState({\n textCustomizedVisible: false\n });\n };\n\n render() {\n return (\n <div>\n <Button onClick={this.onOpenFullyCustomized} type=\"primary\">\n Fully Customized Footer\n </Button> \n <Dialog\n title=\"Welcome to Alibaba.com\"\n footer={<Button warning type=\"primary\" onClick={this.onCloseFullyCustomized}>Customize footer</Button>}\n visible={this.state.fullyCustomizedVisible}\n onOk={this.onCloseFullyCustomized}\n onCancel={this.onCloseFullyCustomized}\n onClose={this.onCloseFullyCustomized}>\n Start your business here by searching a popular product\n </Dialog>\n <Button onClick={this.onOpenTextCustomized} type=\"primary\">\n Text Only Customize\n </Button>\n <Dialog\n title=\"Welcome to Alibaba.com\"\n visible={this.state.textCustomizedVisible}\n onOk={this.onCloseTextCustomized}\n onCancel={this.onCloseTextCustomized}\n onClose={this.onCloseTextCustomized}\n okProps={{children: 'Custom OK', className: 'asdf'}}\n cancelProps={{children: 'Custom Cancel'}}\n >\n Start your business here by searching a popular product\n </Dialog>\n </div>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
默认的 footer 为确定取消两个按钮,你可以自定义 footer 的内容。
\n","order":"2"},"codes":{"jsx":"import { Button, Dialog } from '@alifd/next';\n\n\nclass Demo extends React.Component {\n state = {\n visible: false\n };\n\n onOpenFullyCustomized = () => {\n this.setState({\n fullyCustomizedVisible: true\n });\n };\n\n onCloseFullyCustomized = () => {\n this.setState({\n fullyCustomizedVisible: false\n });\n };\n\n onOpenTextCustomized = () => {\n this.setState({\n textCustomizedVisible: true\n });\n };\n\n onCloseTextCustomized = () => {\n this.setState({\n textCustomizedVisible: false\n });\n };\n\n render() {\n return (\nimport { Button, Dialog } from '@alifd/next';\n\n\nclass Demo extends React.Component {\n state = {\n visible: false\n };\n\n onOpenFullyCustomized = () => {\n this.setState({\n fullyCustomizedVisible: true\n });\n };\n\n onCloseFullyCustomized = () => {\n this.setState({\n fullyCustomizedVisible: false\n });\n };\n\n onOpenTextCustomized = () => {\n this.setState({\n textCustomizedVisible: true\n });\n };\n\n onCloseTextCustomized = () => {\n this.setState({\n textCustomizedVisible: false\n });\n };\n\n render() {\n return (\n <div>\n <Button onClick={this.onOpenFullyCustomized} type=\"primary\">\n Fully Customized Footer\n </Button> \n <Dialog\n title=\"Welcome to Alibaba.com\"\n footer={<Button warning type=\"primary\" onClick={this.onCloseFullyCustomized}>Customize footer</Button>}\n visible={this.state.fullyCustomizedVisible}\n onOk={this.onCloseFullyCustomized}\n onCancel={this.onCloseFullyCustomized}\n onClose={this.onCloseFullyCustomized}>\n Start your business here by searching a popular product\n </Dialog>\n <Button onClick={this.onOpenTextCustomized} type=\"primary\">\n Text Only Customize\n </Button>\n <Dialog\n title=\"Welcome to Alibaba.com\"\n visible={this.state.textCustomizedVisible}\n onOk={this.onCloseTextCustomized}\n onCancel={this.onCloseTextCustomized}\n onClose={this.onCloseTextCustomized}\n okProps={{children: 'Custom OK', className: 'asdf'}}\n cancelProps={{children: 'Custom Cancel'}}\n >\n Start your business here by searching a popular product\n </Dialog>\n </div>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
Use height
prop to set Dialog height style. Will also position footer at bottom.
import { Button, Dialog } from '@alifd/next';\n\n\nclass Demo extends React.Component {\n state = {\n visible: false,\n };\n\n onOpen = () => {\n this.setState({\n visible: true\n });\n }\n\n onClose = () => {\n this.setState({\n visible: false\n });\n };\n\n\n\n render() {\n const { visible } = this.state;\n\n return (\n <div>\n <Button onClick={this.onOpen} type=\"primary\">\n Open dialog\n </Button>\n <Dialog title=\"Fixed Height\"\n visible={visible}\n height=\"400px\"\n onOk={this.onClose}\n onCancel={this.onClose}\n onClose={this.onClose}\n >\n Small Content in a fixed size Dialog\n </Dialog>\n </div>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
使用 'height' 道具设置 Dialog 高度风格。还将页尾底部的位置。
\n","order":"8"},"codes":{"jsx":"import { Button, Dialog } from '@alifd/next';\n\n\nclass Demo extends React.Component {\n state = {\n visible: false,\n };\n\n onOpen = () => {\n this.setState({\n visible: true\n });\n }\n\n onClose = () => {\n this.setState({\n visible: false\n });\n };\n\n\n\n render() {\n const { visible } = this.state;\n\n return (\nimport { Button, Dialog } from '@alifd/next';\n\n\nclass Demo extends React.Component {\n state = {\n visible: false,\n };\n\n onOpen = () => {\n this.setState({\n visible: true\n });\n }\n\n onClose = () => {\n this.setState({\n visible: false\n });\n };\n\n\n\n render() {\n const { visible } = this.state;\n\n return (\n <div>\n <Button onClick={this.onOpen} type=\"primary\">\n Open dialog\n </Button>\n <Dialog title=\"Fixed Height\"\n visible={visible}\n height=\"400px\"\n onOk={this.onClose}\n onCancel={this.onClose}\n onClose={this.onClose}\n >\n Small Content in a fixed size Dialog\n </Dialog>\n </div>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
Use footerActions to control the position of the OK and Cancel buttons and their mutual position. Use footerAlign to control the alignment of the bottom buttons.
\n","order":"1"},"codes":{"jsx":"import { Button, Radio, Dialog } from '@alifd/next';\n\n\nclass Demo extends React.Component {\n state = {\n visible: false,\n footerActions: ['ok', 'cancel'],\n footerAlign: 'right',\n loading: false\n };\n\n onOpen = () => {\n this.setState({\n visible: true\n });\n }\n\n onClose = () => {\n this.setState({\n visible: false\n });\n };\n\n toggleFooterActions = footerActionsStr => {\n this.setState({\n footerActions: footerActionsStr.split(',')\n });\n };\n\n toggleFooterAlign = footerAlign => {\n this.setState({\n footerAlign\n });\n };\n\n toggleOkLoader = loading => {\n this.setState({\n loading\n });\n }\n\n render() {\n const { visible, footerActions, footerAlign, loading } = this.state;\n const okProps = {\n loading\n };\n\n return (\nimport { Button, Radio, Dialog } from '@alifd/next';\n\n\nclass Demo extends React.Component {\n state = {\n visible: false,\n footerActions: ['ok', 'cancel'],\n footerAlign: 'right',\n loading: false\n };\n\n onOpen = () => {\n this.setState({\n visible: true\n });\n }\n\n onClose = () => {\n this.setState({\n visible: false\n });\n };\n\n toggleFooterActions = footerActionsStr => {\n this.setState({\n footerActions: footerActionsStr.split(',')\n });\n };\n\n toggleFooterAlign = footerAlign => {\n this.setState({\n footerAlign\n });\n };\n\n toggleOkLoader = loading => {\n this.setState({\n loading\n });\n }\n\n render() {\n const { visible, footerActions, footerAlign, loading } = this.state;\n const okProps = {\n loading\n };\n\n return (\n <div>\n <Button onClick={this.onOpen} type=\"primary\">\n Open dialog\n </Button>\n <Dialog title=\"Customize buttons of footer\"\n visible={visible}\n footerActions={footerActions}\n footerAlign={footerAlign}\n onOk={this.onClose}\n onCancel={this.onClose}\n onClose={this.onClose}\n okProps={okProps}\n >\n <div className=\"demo-content\">\n <Radio.Group className=\"demo-radio-group\" shape=\"button\" value={footerActions.join(',')} onChange={this.toggleFooterActions}>\n <Radio value=\"ok,cancel\">ok is left</Radio>\n <Radio value=\"cancel,ok\">ok is right</Radio>\n <Radio value=\"ok\">only ok</Radio>\n <Radio value=\"cancel\">only cancel</Radio>\n </Radio.Group>\n <Radio.Group className=\"demo-radio-group\" shape=\"button\" value={footerAlign} onChange={this.toggleFooterAlign}>\n <Radio value=\"left\">left</Radio>\n <Radio value=\"center\">center</Radio>\n <Radio value=\"right\">right</Radio>\n </Radio.Group>\n <Radio.Group className=\"demo-radio-group\" shape=\"button\" value={loading} onChange={this.toggleOkLoader}>\n <Radio value={false}>Loading Off</Radio>\n <Radio value>Loading On</Radio>\n </Radio.Group>\n </div>\n </Dialog>\n </div>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
.demo-content {\n padding: 10px;\n border: 2px dashed #ddd;\n background: #F8F8F8;\n}\n\n.demo-radio-group {\n display: block;\n}\n\n.demo-radio-group + .demo-radio-group {\n margin-top: 10px;\n}
通过 footerActions 来调整确定按钮和取消按钮是否出现以及相互间的位置,通过 footerAlign 来调整底部按钮的对齐方式。
\n","order":"1"},"codes":{"jsx":"import { Button, Radio, Dialog } from '@alifd/next';\n\n\nclass Demo extends React.Component {\n state = {\n visible: false,\n footerActions: ['ok', 'cancel'],\n footerAlign: 'right',\n loading: false\n };\n\n onOpen = () => {\n this.setState({\n visible: true\n });\n }\n\n onClose = () => {\n this.setState({\n visible: false\n });\n };\n\n toggleFooterActions = footerActionsStr => {\n this.setState({\n footerActions: footerActionsStr.split(',')\n });\n };\n\n toggleFooterAlign = footerAlign => {\n this.setState({\n footerAlign\n });\n };\n\n toggleOkLoader = loading => {\n this.setState({\n loading\n });\n }\n\n render() {\n const { visible, footerActions, footerAlign, loading } = this.state;\n const okProps = {\n loading\n };\n\n return (\nimport { Button, Radio, Dialog } from '@alifd/next';\n\n\nclass Demo extends React.Component {\n state = {\n visible: false,\n footerActions: ['ok', 'cancel'],\n footerAlign: 'right',\n loading: false\n };\n\n onOpen = () => {\n this.setState({\n visible: true\n });\n }\n\n onClose = () => {\n this.setState({\n visible: false\n });\n };\n\n toggleFooterActions = footerActionsStr => {\n this.setState({\n footerActions: footerActionsStr.split(',')\n });\n };\n\n toggleFooterAlign = footerAlign => {\n this.setState({\n footerAlign\n });\n };\n\n toggleOkLoader = loading => {\n this.setState({\n loading\n });\n }\n\n render() {\n const { visible, footerActions, footerAlign, loading } = this.state;\n const okProps = {\n loading\n };\n\n return (\n <div>\n <Button onClick={this.onOpen} type=\"primary\">\n Open dialog\n </Button>\n <Dialog title=\"Customize buttons of footer\"\n visible={visible}\n footerActions={footerActions}\n footerAlign={footerAlign}\n onOk={this.onClose}\n onCancel={this.onClose}\n onClose={this.onClose}\n okProps={okProps}\n >\n <div className=\"demo-content\">\n <Radio.Group className=\"demo-radio-group\" shape=\"button\" value={footerActions.join(',')} onChange={this.toggleFooterActions}>\n <Radio value=\"ok,cancel\">ok is left</Radio>\n <Radio value=\"cancel,ok\">ok is right</Radio>\n <Radio value=\"ok\">only ok</Radio>\n <Radio value=\"cancel\">only cancel</Radio>\n </Radio.Group>\n <Radio.Group className=\"demo-radio-group\" shape=\"button\" value={footerAlign} onChange={this.toggleFooterAlign}>\n <Radio value=\"left\">left</Radio>\n <Radio value=\"center\">center</Radio>\n <Radio value=\"right\">right</Radio>\n </Radio.Group>\n <Radio.Group className=\"demo-radio-group\" shape=\"button\" value={loading} onChange={this.toggleOkLoader}>\n <Radio value={false}>Loading Off</Radio>\n <Radio value>Loading On</Radio>\n </Radio.Group>\n </div>\n </Dialog>\n </div>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
.demo-content {\n padding: 10px;\n border: 2px dashed #ddd;\n background: #F8F8F8;\n}\n\n.demo-radio-group {\n display: block;\n}\n\n.demo-radio-group + .demo-radio-group {\n margin-top: 10px;\n}
When the height of the dialog exceeds the viewport height of the browser, the default is to have the scroll bar appear in the body area of the dialog. This ensures that the bottom button can appear directly in the viewport, which is convenient to operate. If you don't want to show a scroll bar, please set isFullScreen to true to show all the content of the dialog.
\n","order":"4"},"codes":{"jsx":"import { Switch, Button, Dialog } from '@alifd/next';\n\n\nconst largeContent = new Array(30).fill(\nStart your business here by searching a popular product
\n);\n\nclass Demo extends React.Component {\n state = {\n visible: false,\n isFullScreen: false,\n closeOnMaskClick: false,\n };\n\n onOpen = () => {\n this.setState({\n visible: true\n });\n };\n\n onClose = () => {\n this.setState({\n visible: false\n });\n };\n\n toggleIsFullScreen = () => {\n this.setState({\n isFullScreen: !this.state.isFullScreen\n });\n }\n\n toggleCloseOnMaskClick = () => {\n this.setState({\n closeOnMaskClick: !this.state.closeOnMaskClick\n });\n }\n\n render() {\n const { visible, isFullScreen, closeOnMaskClick } = this.state;\n\n return (\nStart your business here by searching a popular product
\n);\n\nclass Demo extends React.Component {\n state = {\n visible: false,\n isFullScreen: false,\n closeOnMaskClick: false,\n };\n\n onOpen = () => {\n this.setState({\n visible: true\n });\n };\n\n onClose = () => {\n this.setState({\n visible: false\n });\n };\n\n toggleIsFullScreen = () => {\n this.setState({\n isFullScreen: !this.state.isFullScreen\n });\n }\n\n toggleCloseOnMaskClick = () => {\n this.setState({\n closeOnMaskClick: !this.state.closeOnMaskClick\n });\n }\n\n render() {\n const { visible, isFullScreen, closeOnMaskClick } = this.state;\n\n return (\nimport { Switch, Button, Dialog } from '@alifd/next';\n\n\nconst largeContent = new Array(30).fill(\n <p>Start your business here by searching a popular product</p>\n);\n\nclass Demo extends React.Component {\n state = {\n visible: false,\n isFullScreen: false,\n closeOnMaskClick: false,\n };\n\n onOpen = () => {\n this.setState({\n visible: true\n });\n };\n\n onClose = () => {\n this.setState({\n visible: false\n });\n };\n\n toggleIsFullScreen = () => {\n this.setState({\n isFullScreen: !this.state.isFullScreen\n });\n }\n\n toggleCloseOnMaskClick = () => {\n this.setState({\n closeOnMaskClick: !this.state.closeOnMaskClick\n });\n }\n\n render() {\n const { visible, isFullScreen, closeOnMaskClick } = this.state;\n\n return (\n <div>\n <div style={{ display: 'block', marginBottom: '10px' }}>\n When the height of the dialog exceeds the viewport height of the browser, whether to show the scroll bar:\n </div>\n <Switch style={{ display: 'block', marginBottom: '10px' }} checked={isFullScreen} onChange={this.toggleIsFullScreen} />\n <div style={{ display: 'block', marginBottom: '10px' }}>\n Close on mask click:\n </div>\n <Switch style={{ display: 'block', marginBottom: '10px' }} checked={closeOnMaskClick} onChange={this.toggleCloseOnMaskClick} />\n <Button onClick={this.onOpen} type=\"primary\">\n Open dialog\n </Button>\n <Dialog title=\"Welcome to Alibaba.com\"\n visible={visible}\n isFullScreen={isFullScreen}\n closeable={closeOnMaskClick ? 'close,esc,mask' : 'close,esc'}\n onOk={this.onClose}\n onCancel={this.onClose}\n onClose={this.onClose}>\n {largeContent}\n </Dialog>\n </div>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
Start your business here by searching a popular product
\n);\n\nclass Demo extends React.Component {\n state = {\n visible: false,\n isFullScreen: false,\n closeOnMaskClick: false,\n };\n\n onOpen = () => {\n this.setState({\n visible: true\n });\n };\n\n onClose = () => {\n this.setState({\n visible: false\n });\n };\n\n toggleIsFullScreen = () => {\n this.setState({\n isFullScreen: !this.state.isFullScreen\n });\n }\n\n toggleCloseOnMaskClick = () => {\n this.setState({\n closeOnMaskClick: !this.state.closeOnMaskClick\n });\n }\n\n render() {\n const { visible, isFullScreen, closeOnMaskClick } = this.state;\n\n return (\nStart your business here by searching a popular product
\n);\n\nclass Demo extends React.Component {\n state = {\n visible: false,\n isFullScreen: false,\n closeOnMaskClick: false,\n };\n\n onOpen = () => {\n this.setState({\n visible: true\n });\n };\n\n onClose = () => {\n this.setState({\n visible: false\n });\n };\n\n toggleIsFullScreen = () => {\n this.setState({\n isFullScreen: !this.state.isFullScreen\n });\n }\n\n toggleCloseOnMaskClick = () => {\n this.setState({\n closeOnMaskClick: !this.state.closeOnMaskClick\n });\n }\n\n render() {\n const { visible, isFullScreen, closeOnMaskClick } = this.state;\n\n return (\nimport { Switch, Button, Dialog } from '@alifd/next';\n\n\nconst largeContent = new Array(30).fill(\n <p>Start your business here by searching a popular product</p>\n);\n\nclass Demo extends React.Component {\n state = {\n visible: false,\n isFullScreen: false,\n closeOnMaskClick: false,\n };\n\n onOpen = () => {\n this.setState({\n visible: true\n });\n };\n\n onClose = () => {\n this.setState({\n visible: false\n });\n };\n\n toggleIsFullScreen = () => {\n this.setState({\n isFullScreen: !this.state.isFullScreen\n });\n }\n\n toggleCloseOnMaskClick = () => {\n this.setState({\n closeOnMaskClick: !this.state.closeOnMaskClick\n });\n }\n\n render() {\n const { visible, isFullScreen, closeOnMaskClick } = this.state;\n\n return (\n <div>\n <div style={{ display: 'block', marginBottom: '10px' }}>\n When the height of the dialog exceeds the viewport height of the browser, whether to show the scroll bar:\n </div>\n <Switch style={{ display: 'block', marginBottom: '10px' }} checked={isFullScreen} onChange={this.toggleIsFullScreen} />\n <div style={{ display: 'block', marginBottom: '10px' }}>\n Close on mask click:\n </div>\n <Switch style={{ display: 'block', marginBottom: '10px' }} checked={closeOnMaskClick} onChange={this.toggleCloseOnMaskClick} />\n <Button onClick={this.onOpen} type=\"primary\">\n Open dialog\n </Button>\n <Dialog title=\"Welcome to Alibaba.com\"\n visible={visible}\n isFullScreen={isFullScreen}\n closeable={closeOnMaskClick ? 'close,esc,mask' : 'close,esc'}\n onOk={this.onClose}\n onCancel={this.onClose}\n onClose={this.onClose}>\n {largeContent}\n </Dialog>\n </div>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
When using Dialog.alert, Dialog.confirm, and Dialog.show, if onOk returns a Promise, the dialog will close when the Promise resolves, unless resolve(false)
is called.
import { Button, Message, Dialog } from '@alifd/next';\n\nclass Demo extends React.Component {\n state = {\n visible: false,\n loading: false,\n };\n\n onOpen = () => {\n this.setState({\n visible: true\n });\n };\n\n onOk = () => {\n return new Promise(resolve => {\n this.setState({\n loading: true\n });\n setTimeout(resolve, 2000);\n }).then(() => {\n Message.success('Deleted successfully!');\n this.setState({\n loading: false,\n visible: false\n });\n });\n };\n\n onClose = () => {\n this.setState({\n visible: false\n });\n };\n\n render() {\n const okProps = {\n loading: this.state.loading\n };\n return (\n <div>\n <Button onClick={this.onOpen} type=\"primary\">\n Dialog Promise\n </Button>\n <Dialog\n title=\"Welcome to Alibaba.com\"\n visible={this.state.visible}\n okProps={okProps}\n onOk={this.onOk}\n onCancel={this.onClose}\n onClose={this.onClose}>\n Start your business here by searching a popular product\n </Dialog>\n </div>\n );\n }\n}\n\nconst popupConfirm = () => {\n Dialog.confirm({\n title: 'Confirm',\n content: 'Do you confirm deleting this content?',\n onOk: () => {\n return new Promise(resolve => {\n setTimeout(resolve, 2000);\n }).then(() => {\n Message.success('Deleted successfully!');\n });\n }\n });\n};\n\nReactDOM.render(<div>\n <Demo />\n <Button type=\"primary\" warning onClick={popupConfirm}>Quick Confirm Promise</Button>\n</div>\n, mountNode);
在使用 Dialog.alert,Dialog.confirm 以及 Dialog.show 时,如果 onOk 返回 Promise,对话框会在 Promise resolve 时关闭,除非调用 resolve(false)
。
import { Button, Message, Dialog } from '@alifd/next';\n\nclass Demo extends React.Component {\n state = {\n visible: false,\n loading: false,\n };\n\n onOpen = () => {\n this.setState({\n visible: true\n });\n };\n\n onOk = () => {\n return new Promise(resolve => {\n this.setState({\n loading: true\n });\n setTimeout(resolve, 2000);\n }).then(() => {\n Message.success('Deleted successfully!');\n this.setState({\n loading: false,\n visible: false\n });\n });\n };\n\n onClose = () => {\n this.setState({\n visible: false\n });\n };\n\n render() {\n const okProps = {\n loading: this.state.loading\n };\n return (\n <div>\n <Button onClick={this.onOpen} type=\"primary\">\n Dialog Promise\n </Button>\n <Dialog\n title=\"Welcome to Alibaba.com\"\n visible={this.state.visible}\n okProps={okProps}\n onOk={this.onOk}\n onCancel={this.onClose}\n onClose={this.onClose}>\n Start your business here by searching a popular product\n </Dialog>\n </div>\n );\n }\n}\n\nconst popupConfirm = () => {\n Dialog.confirm({\n title: 'Confirm',\n content: 'Do you confirm deleting this content?',\n onOk: () => {\n return new Promise(resolve => {\n setTimeout(resolve, 2000);\n }).then(() => {\n Message.success('Deleted successfully!');\n });\n }\n });\n};\n\nReactDOM.render(<div>\n <Demo />\n <Button type=\"primary\" warning onClick={popupConfirm}>Quick Confirm Promise</Button>\n</div>\n, mountNode);
The Dialog provides quick methods called alert and confirm, as well as a lower-level show method.
\n","order":"5"},"codes":{"jsx":"import { Button, Dialog, ConfigProvider } from '@alifd/next';\n\nconst popupAlert = () => {\n Dialog.alert({\n title: 'Alert',\n content: 'alert content alert content...',\n okProps: {children: 'Custom OK' },\n onOk: () => console.log('ok')\n });\n};\n\nconst popupConfirm = () => {\n Dialog.confirm({\n title: 'Confirm',\n content: 'confirm content confirm content...',\n onOk: () => console.log('ok'),\n onCancel: () => console.log('cancel')\n });\n};\n\nconst popupShow = () => {\n const dialog = Dialog.show({\n title: 'Custom',\n content: 'custom content custom content...',\n footer: (\n \n )\n });\n};\n\nconst popupCustomIcon = () => {\n Dialog.confirm({\n title: 'Confirm',\n content: 'set icon as \"warning\" ',\n messageProps:{\n type: 'warning'\n },\n onOk: () => console.log('ok'),\n onCancel: () => console.log('cancel')\n });\n};\n\nReactDOM.render(\nimport { Button, Dialog, ConfigProvider } from '@alifd/next';\n\nconst popupAlert = () => {\n Dialog.alert({\n title: 'Alert',\n content: 'alert content alert content...',\n okProps: {children: 'Custom OK' },\n onOk: () => console.log('ok')\n });\n};\n\nconst popupConfirm = () => {\n Dialog.confirm({\n title: 'Confirm',\n content: 'confirm content confirm content...',\n onOk: () => console.log('ok'),\n onCancel: () => console.log('cancel')\n });\n};\n\nconst popupShow = () => {\n const dialog = Dialog.show({\n title: 'Custom',\n content: 'custom content custom content...',\n footer: (\n <Button warning type=\"primary\" onClick={() => dialog.hide()}>\n Custom button\n </Button>\n )\n });\n};\n\nconst popupCustomIcon = () => {\n Dialog.confirm({\n title: 'Confirm',\n content: 'set icon as \"warning\" ',\n messageProps:{\n type: 'warning'\n },\n onOk: () => console.log('ok'),\n onCancel: () => console.log('cancel')\n });\n};\n\nReactDOM.render(\n <ConfigProvider locale={{ Dialog: { ok: 'OK', cancel: 'Cancel' } }}>\n <span>\n <Button onClick={popupAlert}>Alert</Button> \n <Button onClick={popupConfirm}>Confirm</Button> \n <Button onClick={popupShow}>Show</Button> \n <Button onClick={popupCustomIcon}>Custom Icon</Button>\n </span>\n </ConfigProvider>,\n mountNode\n);
Dialog 提供 alert 和 confirm 的快掉调用方式,以及更底层的 show 方式。
\n","order":"5"},"codes":{"jsx":"import { Button, Dialog, ConfigProvider } from '@alifd/next';\n\nconst popupAlert = () => {\n Dialog.alert({\n title: 'Alert',\n content: 'alert content alert content...',\n okProps: {children: 'Custom OK' },\n onOk: () => console.log('ok')\n });\n};\n\nconst popupConfirm = () => {\n Dialog.confirm({\n title: 'Confirm',\n content: 'confirm content confirm content...',\n onOk: () => console.log('ok'),\n onCancel: () => console.log('cancel')\n });\n};\n\nconst popupShow = () => {\n const dialog = Dialog.show({\n title: 'Custom',\n content: 'custom content custom content...',\n footer: (\n \n )\n });\n};\n\nconst popupCustomIcon = () => {\n Dialog.confirm({\n title: 'Confirm',\n content: 'set icon as \"warning\" ',\n messageProps:{\n type: 'warning'\n },\n onOk: () => console.log('ok'),\n onCancel: () => console.log('cancel')\n });\n};\n\nReactDOM.render(\nimport { Button, Dialog, ConfigProvider } from '@alifd/next';\n\nconst popupAlert = () => {\n Dialog.alert({\n title: 'Alert',\n content: 'alert content alert content...',\n okProps: {children: 'Custom OK' },\n onOk: () => console.log('ok')\n });\n};\n\nconst popupConfirm = () => {\n Dialog.confirm({\n title: 'Confirm',\n content: 'confirm content confirm content...',\n onOk: () => console.log('ok'),\n onCancel: () => console.log('cancel')\n });\n};\n\nconst popupShow = () => {\n const dialog = Dialog.show({\n title: 'Custom',\n content: 'custom content custom content...',\n footer: (\n <Button warning type=\"primary\" onClick={() => dialog.hide()}>\n Custom button\n </Button>\n )\n });\n};\n\nconst popupCustomIcon = () => {\n Dialog.confirm({\n title: 'Confirm',\n content: 'set icon as \"warning\" ',\n messageProps:{\n type: 'warning'\n },\n onOk: () => console.log('ok'),\n onCancel: () => console.log('cancel')\n });\n};\n\nReactDOM.render(\n <ConfigProvider locale={{ Dialog: { ok: 'OK', cancel: 'Cancel' } }}>\n <span>\n <Button onClick={popupAlert}>Alert</Button> \n <Button onClick={popupConfirm}>Confirm</Button> \n <Button onClick={popupShow}>Show</Button> \n <Button onClick={popupCustomIcon}>Custom Icon</Button>\n </span>\n </ConfigProvider>,\n mountNode\n);
Update the position of the dialog by setting shouldUpdatePosition to true. It is generally used to change the contents of the dialog but still ensure the original alignment.
\n","order":"3"},"codes":{"jsx":"import { Switch, Button, Dialog } from '@alifd/next';\n\n\nconst shortContent =Start your business here by searching a popular product
;\nconst longContent = [\nStart your business here by searching a popular product
,\nStart your business here by searching a popular product
,\nStart your business here by searching a popular product
,\nStart your business here by searching a popular product
\n];\n\nclass App extends React.Component {\n state = {\n visible: false,\n short: true,\n shouldUpdatePosition: true\n }\n\n onOpen = () => {\n this.setState({\n visible: true,\n short: true\n });\n };\n\n onClose = () => {\n this.setState({\n visible: false\n });\n };\n\n toggleShouldUpdatePosition = () => {\n this.setState({\n shouldUpdatePosition: !this.state.shouldUpdatePosition\n });\n };\n\n modifyContent = () => {\n this.setState({\n short: !this.state.short\n });\n };\n\n render() {\n const { visible, short, shouldUpdatePosition } = this.state;\n\n return (\nStart your business here by searching a popular product
;\nconst longContent = [\nStart your business here by searching a popular product
,\nStart your business here by searching a popular product
,\nStart your business here by searching a popular product
,\nStart your business here by searching a popular product
\n];\n\nclass App extends React.Component {\n state = {\n visible: false,\n short: true,\n shouldUpdatePosition: true\n }\n\n onOpen = () => {\n this.setState({\n visible: true,\n short: true\n });\n };\n\n onClose = () => {\n this.setState({\n visible: false\n });\n };\n\n toggleShouldUpdatePosition = () => {\n this.setState({\n shouldUpdatePosition: !this.state.shouldUpdatePosition\n });\n };\n\n modifyContent = () => {\n this.setState({\n short: !this.state.short\n });\n };\n\n render() {\n const { visible, short, shouldUpdatePosition } = this.state;\n\n return (\nimport { Switch, Button, Dialog } from '@alifd/next';\n\n\nconst shortContent = <p>Start your business here by searching a popular product</p>;\nconst longContent = [\n <p key=\"0\">Start your business here by searching a popular product</p>,\n <p key=\"1\">Start your business here by searching a popular product</p>,\n <p key=\"2\">Start your business here by searching a popular product</p>,\n <p key=\"3\">Start your business here by searching a popular product</p>\n];\n\nclass App extends React.Component {\n state = {\n visible: false,\n short: true,\n shouldUpdatePosition: true\n }\n\n onOpen = () => {\n this.setState({\n visible: true,\n short: true\n });\n };\n\n onClose = () => {\n this.setState({\n visible: false\n });\n };\n\n toggleShouldUpdatePosition = () => {\n this.setState({\n shouldUpdatePosition: !this.state.shouldUpdatePosition\n });\n };\n\n modifyContent = () => {\n this.setState({\n short: !this.state.short\n });\n };\n\n render() {\n const { visible, short, shouldUpdatePosition } = this.state;\n\n return (\n <div>\n <div style={{ display: 'block', marginBottom: '10px' }}>\n Whether to update the dialog position when the dialog height changes:\n </div>\n <Switch style={{ display: 'block', marginBottom: '10px' }} checked={shouldUpdatePosition} onChange={this.toggleShouldUpdatePosition} />\n <Button onClick={this.onOpen} type=\"primary\">\n Open dialog\n </Button>\n <Dialog title=\"Welcome to Alibaba.com\"\n visible={visible}\n onOk={this.onClose.bind(this, 'okClick')}\n onCancel={this.onClose.bind(this, 'cancelClick')}\n onClose={this.onClose}\n shouldUpdatePosition={shouldUpdatePosition}>\n <Button type=\"primary\" onClick={this.modifyContent}>\n Change content\n </Button>\n {short ? shortContent : longContent}\n </Dialog>\n </div>\n );\n }\n}\n\nReactDOM.render(<App/>, mountNode);
通过设置 shouldUpdatePosition 为 true 来及时更新对话框的位置,一般用于对话框内容发生变化但是仍然要保证原来对齐方式的情况
\n","order":"3"},"codes":{"jsx":"import { Switch, Button, Dialog } from '@alifd/next';\n\n\nconst shortContent =Start your business here by searching a popular product
;\nconst longContent = [\nStart your business here by searching a popular product
,\nStart your business here by searching a popular product
,\nStart your business here by searching a popular product
,\nStart your business here by searching a popular product
\n];\n\nclass App extends React.Component {\n state = {\n visible: false,\n short: true,\n shouldUpdatePosition: true\n }\n\n onOpen = () => {\n this.setState({\n visible: true,\n short: true\n });\n };\n\n onClose = () => {\n this.setState({\n visible: false\n });\n };\n\n toggleShouldUpdatePosition = () => {\n this.setState({\n shouldUpdatePosition: !this.state.shouldUpdatePosition\n });\n };\n\n modifyContent = () => {\n this.setState({\n short: !this.state.short\n });\n };\n\n render() {\n const { visible, short, shouldUpdatePosition } = this.state;\n\n return (\nStart your business here by searching a popular product
;\nconst longContent = [\nStart your business here by searching a popular product
,\nStart your business here by searching a popular product
,\nStart your business here by searching a popular product
,\nStart your business here by searching a popular product
\n];\n\nclass App extends React.Component {\n state = {\n visible: false,\n short: true,\n shouldUpdatePosition: true\n }\n\n onOpen = () => {\n this.setState({\n visible: true,\n short: true\n });\n };\n\n onClose = () => {\n this.setState({\n visible: false\n });\n };\n\n toggleShouldUpdatePosition = () => {\n this.setState({\n shouldUpdatePosition: !this.state.shouldUpdatePosition\n });\n };\n\n modifyContent = () => {\n this.setState({\n short: !this.state.short\n });\n };\n\n render() {\n const { visible, short, shouldUpdatePosition } = this.state;\n\n return (\nimport { Switch, Button, Dialog } from '@alifd/next';\n\n\nconst shortContent = <p>Start your business here by searching a popular product</p>;\nconst longContent = [\n <p key=\"0\">Start your business here by searching a popular product</p>,\n <p key=\"1\">Start your business here by searching a popular product</p>,\n <p key=\"2\">Start your business here by searching a popular product</p>,\n <p key=\"3\">Start your business here by searching a popular product</p>\n];\n\nclass App extends React.Component {\n state = {\n visible: false,\n short: true,\n shouldUpdatePosition: true\n }\n\n onOpen = () => {\n this.setState({\n visible: true,\n short: true\n });\n };\n\n onClose = () => {\n this.setState({\n visible: false\n });\n };\n\n toggleShouldUpdatePosition = () => {\n this.setState({\n shouldUpdatePosition: !this.state.shouldUpdatePosition\n });\n };\n\n modifyContent = () => {\n this.setState({\n short: !this.state.short\n });\n };\n\n render() {\n const { visible, short, shouldUpdatePosition } = this.state;\n\n return (\n <div>\n <div style={{ display: 'block', marginBottom: '10px' }}>\n Whether to update the dialog position when the dialog height changes:\n </div>\n <Switch style={{ display: 'block', marginBottom: '10px' }} checked={shouldUpdatePosition} onChange={this.toggleShouldUpdatePosition} />\n <Button onClick={this.onOpen} type=\"primary\">\n Open dialog\n </Button>\n <Dialog title=\"Welcome to Alibaba.com\"\n visible={visible}\n onOk={this.onClose.bind(this, 'okClick')}\n onCancel={this.onClose.bind(this, 'cancelClick')}\n onClose={this.onClose}\n shouldUpdatePosition={shouldUpdatePosition}>\n <Button type=\"primary\" onClick={this.modifyContent}>\n Change content\n </Button>\n {short ? shortContent : longContent}\n </Dialog>\n </div>\n );\n }\n}\n\nReactDOM.render(<App/>, mountNode);
The dialog is used to provide the user with an auxiliary window for quickly performing a simple operation, confirming user information, or providing a feedback prompt without leaving the main path.
\nParam | \nDescripiton | \nType | \nDefault Value | \n
---|---|---|---|
visible | \nwhether is visible | \nBoolean | \nfalse | \n
title | \ntitle of dialog | \nReactNode | \n- | \n
children | \ncontent of dialog | \nReactNode | \n- | \n
footer | \nbottom content, if yout set to false, will not display | \nBoolean/ReactNode | \n[<Button type="primary">Ok</Button>, <Button>Cancel</Button>] | \n
footerAlign | \nalignment of footer option: 'left', 'center', 'right' | \nEnum | \n'right' | \n
footerActions | \nspecify whether the ok button and the cancel button exist and how they are arranged option: ['ok', 'cancel'] (The ok and the cancel buttons exist at the same time, and the ok button is on the left) ['cancel', 'ok'] (The ok and the cancel buttons exist at the same time, and the cancel button is on the left) ['ok'] (only ok button exists) ['cancel'] (only cancel button exists) | \nArray | \n['ok', 'cancel'] | \n
onOk | \ncallback function triggered when the ok button is clicked signatures: Function(event: Object) => void params: event: {Object} clicked event | \nFunction | \n() => {} | \n
onCancel | \ncallback function triggered when the cancel button is clicked signatures: Function(event: Object) => void params: event: {Object} clicked event | \nFunction | \n() => {} | \n
okProps | \nproperties of the ok button | \nObject | \n{} | \n
cancelProps | \nproperties of the cancel button | \nObject | \n{} | \n
closeable | \ncontrols how the dialog is closed. The value can be either a String or Boolean, where the string consists of the following values: close clicking the close button can close the dialog mask clicking the mask can close the dialog esc pressing the esc key can close the dialog such as 'close' or 'close,esc,mask' If set to true, all of the above close methods take effect If set to false, all of the above close methods will fail | \nString/Boolean | \n'esc,close' | \n
onClose | \ncallback function triggered when the dialog closes signatures: Function(trigger: String, event: Object) => void params: trigger: {String} behavior triggered closed event: {Object} closed event | \nFunction | \n() => {} | \n
afterClose | \ncallback function triggered after the dialog closed, if enabel animation, it will trigger after the animation ends. signatures: Function() => void | \nFunction | \n() => {} | \n
hasMask | \nwhether to has mask | \nBoolean | \ntrue | \n
animation | \nopen and close animation class name | \nObject/Boolean | \n{ in: 'fadeInDown', out: 'fadeOutUp' } | \n
autoFocus | \nwhether to focus the element in the dialog automatically when the dialog is opened | \nBoolean | \nfalse | \n
align | \nalignment of dialog, @see overlay docs for detail | \nString/Boolean | \n'cc cc' | \n
isFullScreen | \nwhen the height of the dialog exceeds the viewport height of the browser, whether to display all content of dialog or display scrollbars to ensure that the dialog is fully displayed in the viewport. This property is only effective when the dialog is vertically horizontally centered, that is, align is set to 'cc cc' | \nBoolean | \nfalse | \n
shouldUpdatePosition | \nwhether to update the dialog position when the dialog is rerendered. It is generally used to ensure the original alignment after the height of the dialog changes. | \nBoolean | \nfalse | \n
minMargin | \nthe minimum distance between the dialog box at the top and bottom of the browser, it will not work if set align to 'cc cc' and set isFullScreen to true | \nNumber | \n40 | \n
overlayProps | \nproperties of Overlay | \nObject | \n{} | \n
height | \nheight style attribute for dialog | \nString | \n- | \n
The following only list common properties that config can pass, and other properties of the Dialog can also be passed in.
\nParam | \nDescripiton | \nType | \nDefault Value | \n
---|---|---|---|
title | \ntitle of dialog | \nReactNode | \n'' | \n
content | \ncontent of dialog | \nReactNode | \n'' | \n
onOk | \ncallback function triggered when the ok button is clicked | \nFunction | \n() => {} | \n
onCancel | \ncallback function triggered when the cancel button is clicked | \nFunction | \n() => {} | \n
messageProps | \nproperties of Message | \nObject | \n{} | \n
The following only list common properties that config can pass, and other properties of the Dialog can also be passed in.
\nParam | \nDescripiton | \nType | \nDefault Value | \n
---|---|---|---|
title | \ntitle of dialog | \nReactNode | \n'' | \n
content | \ncontent of dialog | \nReactNode | \n'' | \n
onOk | \ncallback function triggered when the ok button is clicked | \nFunction | \n() => {} | \n
onCancel | \ncallback function triggered when the cancel button is clicked | \nFunction | \n() => {} | \n
The Dialog uses JS for positioning by default. When the content is too long, JS automatically adjusts the height of the dialog so that the action button appears in the visible area. However, this may result in the inability to perceive the reuse of JS positioning when the height of the dialog changes. There are two solutions:
\nSet shouldUpdatePosition
to true to reposition after content is updated.
Use isFullScreen
to enable CSS positioning. It can be adaptively centered no matter how the height of the dialog changes, but the action button cannot appear in the visible area when the content is too long.
Keyboard | \nDescripiton | \n
---|---|
esc | \npressing ESC will close dialog | \n
tab | \nfocus on any element that can be focused, the focus remains in the dialog when the dialog is displayed | \n
shift+tab | \nback focus on any element that can be focused, the focus remains in the dialog when the dialog is displayed | \n
对话框
\n对话框是用于在不离开主路径的情况下,提供用户快速执行简单的操作、确认用户信息或反馈提示的辅助窗口。
\n参数 | \n说明 | \n类型 | \n默认值 | \n
---|---|---|---|
visible | \n是否显示 | \nBoolean | \nfalse | \n
title | \n标题 | \nReactNode | \n- | \n
children | \n内容 | \nReactNode | \n- | \n
footer | \n底部内容,设置为 false,则不进行显示 | \nBoolean/ReactNode | \n[<Button type="primary">确定</Button>, <Button>取消</Button>] | \n
footerAlign | \n底部按钮的对齐方式 可选值: 'left', 'center', 'right' | \nEnum | \n'right' | \n
footerActions | \n指定确定按钮和取消按钮是否存在以及如何排列, 可选值: ['ok', 'cancel'](确认取消按钮同时存在,确认按钮在左) ['cancel', 'ok'](确认取消按钮同时存在,确认按钮在右) ['ok'](只存在确认按钮) ['cancel'](只存在取消按钮) | \nArray | \n['ok', 'cancel'] | \n
onOk | \n在点击确定按钮时触发的回调函数 签名: Function(event: Object) => void 参数: event: {Object} 点击事件对象 | \nFunction | \n() => {} | \n
onCancel | \n在点击取消按钮时触发的回调函数 签名: Function(event: Object) => void 参数: event: {Object} 点击事件对象 | \nFunction | \n() => {} | \n
okProps | \n应用于确定按钮的属性对象 | \nObject | \n{} | \n
cancelProps | \n应用于取消按钮的属性对象 | \nObject | \n{} | \n
closeable | \n控制对话框关闭的方式,值可以为字符串或者布尔值,其中字符串是由以下值组成: close 表示点击关闭按钮可以关闭对话框 mask 表示点击遮罩区域可以关闭对话框 esc 表示按下 esc 键可以关闭对话框 如 'close' 或 'close,esc,mask' 如果设置为 true,则以上关闭方式全部生效 如果设置为 false,则以上关闭方式全部失效 | \nString/Boolean | \n'esc,close' | \n
onClose | \n对话框关闭时触发的回调函数 签名: Function(trigger: String, event: Object) => void 参数: trigger: {String} 关闭触发行为的描述字符串 event: {Object} 关闭时事件对象 | \nFunction | \n() => {} | \n
afterClose | \n对话框关闭后触发的回调函数, 如果有动画,则在动画结束后触发 签名: Function() => void | \nFunction | \n() => {} | \n
hasMask | \n是否显示遮罩 | \nBoolean | \ntrue | \n
animation | \n显示隐藏时动画的播放方式 | \nObject/Boolean | \n{ in: 'fadeInDown', out: 'fadeOutUp', } | \n
autoFocus | \n对话框弹出时是否自动获得焦点 | \nBoolean | \nfalse | \n
align | \n对话框对齐方式, 具体见Overlay文档 | \nString/Boolean | \n'cc cc' | \n
isFullScreen | \n当对话框高度超过浏览器视口高度时,是否显示所有内容而不是出现滚动条以保证对话框完整显示在浏览器视口内,该属性仅在对话框垂直水平居中时生效,即 align 被设置为 'cc cc' 时 | \nBoolean | \nfalse | \n
shouldUpdatePosition | \n是否在对话框重新渲染时及时更新对话框位置,一般用于对话框高度变化后依然能保证原来的对齐方式 | \nBoolean | \nfalse | \n
minMargin | \n对话框距离浏览器顶部和底部的最小间距,align 被设置为 'cc cc' 并且 isFullScreen 被设置为 true 时不生效 | \nNumber | \n40 | \n
overlayProps | \n透传到弹层组件的属性对象 | \nObject | \n{} | \n
height | \n对话框的高度样式属性 | \nString | \n- | \n
以下只列举 config 可以传入的常用属性,Dialog 组件的其他属性也可以传入
\n属性 | \n说明 | \n类型 | \n默认值 | \n
---|---|---|---|
title | \n标题 | \nReactNode | \n'' | \n
content | \n内容 | \nReactNode | \n'' | \n
onOk | \n在点击确定按钮时触发的回调函数 | \nFunction | \n() => {} | \n
onCancel | \n在点击取消按钮时触发的回调函数 | \nFunction | \n() => {} | \n
messageProps | \n内嵌 Message 组件属性对象 | \nObject | \n{} | \n
以下只列举 config 可以传入的常用属性,Dialog 组件其他属性也可以传入
\n属性 | \n说明 | \n类型 | \n默认值 | \n
---|---|---|---|
title | \n标题 | \nReactNode | \n'' | \n
content | \n内容 | \nReactNode | \n'' | \n
onOk | \n在点击确定按钮时触发的回调函数 | \nFunction | \n() => {} | \n
onCancel | \n在点击取消按钮时触发的回调函数 | \nFunction | \n() => {} | \n
Dialog 组件默认使用 JS 进行定位,当内容过长时使用 JS 自动调整对话框高度,以使得操作按钮在可视区域内出现,但是这会造成在对话框高度发生变化时无法感知重新使用 JS 定位,有下面两种解决方案:
\n设置 shouldUpdatePosition
,在内容更新后,会重新进行定位。
使用 isFullScreen
,启动 CSS 进行定位,无论对话框高度如何变化都能自适应居中,但是当内容过长时无法让操作按钮在可视区域内出现。
键盘 | \n说明 | \n
---|---|
esc | \n按下ESC键将会关闭dialog而不触发任何的动作 | \n
tab | \n正向聚焦到任何可以被聚焦的元素, 在Dialog显示的时候,焦点始终保持在框体内 | \n
shift+tab | \n反向聚焦到任何可以被聚焦的元素,在Dialog显示的时候,焦点始终保持在框体内 | \n
First drawer
\n","order":"0"},"codes":{"jsx":"import { Button, Drawer } from '@alifd/next';\n\nclass Demo extends React.Component {\n state = {\n visible: false,\n };\n\n onOpen = () => {\n this.setState({\n visible: true\n });\n };\n\n onClose = (reason, e) => {\n console.log('onClose: ', reason, e);\n this.setState({\n visible: false\n });\n }\n\n render() {\n return (\nimport { Button, Drawer } from '@alifd/next';\n\nclass Demo extends React.Component {\n state = {\n visible: false,\n };\n\n onOpen = () => {\n this.setState({\n visible: true\n });\n };\n\n onClose = (reason, e) => {\n console.log('onClose: ', reason, e);\n this.setState({\n visible: false\n });\n }\n\n render() {\n return (\n <div>\n <Button type=\"primary\" onClick={this.onOpen}> open </Button>\n <Drawer\n title=\"标题\"\n placement=\"right\"\n visible={this.state.visible}\n onClose={this.onClose}>\n Start your business here by searching a popular product\n </Drawer>\n </div>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
第一个抽屉
\n","order":"0"},"codes":{"jsx":"import { Button, Drawer } from '@alifd/next';\n\nclass Demo extends React.Component {\n state = {\n visible: false,\n };\n\n onOpen = () => {\n this.setState({\n visible: true\n });\n };\n\n onClose = (reason, e) => {\n console.log('onClose: ', reason, e);\n this.setState({\n visible: false\n });\n }\n\n render() {\n return (\nimport { Button, Drawer } from '@alifd/next';\n\nclass Demo extends React.Component {\n state = {\n visible: false,\n };\n\n onOpen = () => {\n this.setState({\n visible: true\n });\n };\n\n onClose = (reason, e) => {\n console.log('onClose: ', reason, e);\n this.setState({\n visible: false\n });\n }\n\n render() {\n return (\n <div>\n <Button type=\"primary\" onClick={this.onOpen}> open </Button>\n <Drawer\n title=\"标题\"\n placement=\"right\"\n visible={this.state.visible}\n onClose={this.onClose}>\n Start your business here by searching a popular product\n </Drawer>\n </div>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
Double drawer
\n","order":"2"},"codes":{"jsx":"import { Button, Drawer } from '@alifd/next';\n\nclass App extends React.Component {\n state = { visible: false, childrenDrawer: false };\n\n showDrawer = () => {\n this.setState({\n visible: true,\n });\n };\n\n onClose = () => {\n this.setState({\n visible: false,\n });\n };\n\n showChildrenDrawer = () => {\n this.setState({\n childrenDrawer: true,\n });\n };\n\n onChildrenDrawerClose = () => {\n this.setState({\n childrenDrawer: false,\n });\n };\n\n render() {\n return (\nimport { Button, Drawer } from '@alifd/next';\n\nclass App extends React.Component {\n state = { visible: false, childrenDrawer: false };\n\n showDrawer = () => {\n this.setState({\n visible: true,\n });\n };\n\n onClose = () => {\n this.setState({\n visible: false,\n });\n };\n\n showChildrenDrawer = () => {\n this.setState({\n childrenDrawer: true,\n });\n };\n\n onChildrenDrawerClose = () => {\n this.setState({\n childrenDrawer: false,\n });\n };\n\n render() {\n return (\n <div>\n <Button type=\"primary\" onClick={this.showDrawer}>\n Open drawer\n </Button>\n <Drawer\n title=\"Multi-level drawer\"\n width={520}\n closeable={'mask'}\n onClose={this.onClose}\n visible={this.state.visible}\n >\n <Button type=\"primary\" onClick={this.showChildrenDrawer}>\n Two-level drawer\n </Button>\n <Drawer\n title=\"Two-level Drawer\"\n width={320}\n closeable={'mask'}\n onClose={this.onChildrenDrawerClose}\n visible={this.state.childrenDrawer}\n >\n This is two-level drawer\n </Drawer>\n <div\n style={{\n position: 'absolute',\n bottom: 0,\n width: '100%',\n borderTop: '1px solid #e8e8e8',\n padding: '10px 16px',\n textAlign: 'right',\n left: 0,\n background: '#fff',\n borderRadius: '0 0 4px 4px',\n }}\n >\n <Button\n style={{\n marginRight: 8,\n }}\n onClick={this.onClose}\n >\n Cancel\n </Button>\n <Button onClick={this.onClose} type=\"primary\">\n Submit\n </Button>\n </div>\n </Drawer>\n </div>\n );\n }\n}\n\nReactDOM.render(<App />, mountNode);
双层抽屉,抽屉内打开新的抽屉
\n","order":"2"},"codes":{"jsx":"import { Button, Drawer } from '@alifd/next';\n\nclass App extends React.Component {\n state = { visible: false, childrenDrawer: false };\n\n showDrawer = () => {\n this.setState({\n visible: true,\n });\n };\n\n onClose = () => {\n this.setState({\n visible: false,\n });\n };\n\n showChildrenDrawer = () => {\n this.setState({\n childrenDrawer: true,\n });\n };\n\n onChildrenDrawerClose = () => {\n this.setState({\n childrenDrawer: false,\n });\n };\n\n render() {\n return (\nimport { Button, Drawer } from '@alifd/next';\n\nclass App extends React.Component {\n state = { visible: false, childrenDrawer: false };\n\n showDrawer = () => {\n this.setState({\n visible: true,\n });\n };\n\n onClose = () => {\n this.setState({\n visible: false,\n });\n };\n\n showChildrenDrawer = () => {\n this.setState({\n childrenDrawer: true,\n });\n };\n\n onChildrenDrawerClose = () => {\n this.setState({\n childrenDrawer: false,\n });\n };\n\n render() {\n return (\n <div>\n <Button type=\"primary\" onClick={this.showDrawer}>\n Open drawer\n </Button>\n <Drawer\n title=\"Multi-level drawer\"\n width={520}\n closeable={'mask'}\n onClose={this.onClose}\n visible={this.state.visible}\n >\n <Button type=\"primary\" onClick={this.showChildrenDrawer}>\n Two-level drawer\n </Button>\n <Drawer\n title=\"Two-level Drawer\"\n width={320}\n closeable={'mask'}\n onClose={this.onChildrenDrawerClose}\n visible={this.state.childrenDrawer}\n >\n This is two-level drawer\n </Drawer>\n <div\n style={{\n position: 'absolute',\n bottom: 0,\n width: '100%',\n borderTop: '1px solid #e8e8e8',\n padding: '10px 16px',\n textAlign: 'right',\n left: 0,\n background: '#fff',\n borderRadius: '0 0 4px 4px',\n }}\n >\n <Button\n style={{\n marginRight: 8,\n }}\n onClick={this.onClose}\n >\n Cancel\n </Button>\n <Button onClick={this.onClose} type=\"primary\">\n Submit\n </Button>\n </div>\n </Drawer>\n </div>\n );\n }\n}\n\nReactDOM.render(<App />, mountNode);
Diffrent placement
\n","order":"1"},"codes":{"jsx":"import { Radio, Button, Drawer } from '@alifd/next';\n\nclass Demo extends React.Component {\n state = {\n visible: false,\n placement: 'right'\n };\n\n onOpen = () => {\n this.setState({\n visible: true\n });\n };\n\n onClose = (reason) => {\n\n this.setState({\n visible: false\n });\n };\n\n onPlacementChange = dir => {\n this.setState({\n placement: dir\n });\n }\n\n render() {\n return (\nimport { Radio, Button, Drawer } from '@alifd/next';\n\nclass Demo extends React.Component {\n state = {\n visible: false,\n placement: 'right'\n };\n\n onOpen = () => {\n this.setState({\n visible: true\n });\n };\n\n onClose = (reason) => {\n\n this.setState({\n visible: false\n });\n };\n\n onPlacementChange = dir => {\n this.setState({\n placement: dir\n });\n }\n\n render() {\n return (\n <div>\n <Radio.Group\n dataSource={['right', 'bottom', 'left', 'top']}\n defaultValue={'right'}\n onChange={this.onPlacementChange}\n /> \n <Button type=\"primary\" onClick={this.onOpen}> open </Button>\n <Drawer\n title=\"标题\"\n visible={this.state.visible}\n placement={this.state.placement}\n onClose={this.onClose}>\n Start your business here by searching a popular product\n </Drawer>\n </div>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
自定义弹出方向
\n","order":"1"},"codes":{"jsx":"import { Radio, Button, Drawer } from '@alifd/next';\n\nclass Demo extends React.Component {\n state = {\n visible: false,\n placement: 'right'\n };\n\n onOpen = () => {\n this.setState({\n visible: true\n });\n };\n\n onClose = (reason) => {\n\n this.setState({\n visible: false\n });\n };\n\n onPlacementChange = dir => {\n this.setState({\n placement: dir\n });\n }\n\n render() {\n return (\nimport { Radio, Button, Drawer } from '@alifd/next';\n\nclass Demo extends React.Component {\n state = {\n visible: false,\n placement: 'right'\n };\n\n onOpen = () => {\n this.setState({\n visible: true\n });\n };\n\n onClose = (reason) => {\n\n this.setState({\n visible: false\n });\n };\n\n onPlacementChange = dir => {\n this.setState({\n placement: dir\n });\n }\n\n render() {\n return (\n <div>\n <Radio.Group\n dataSource={['right', 'bottom', 'left', 'top']}\n defaultValue={'right'}\n onChange={this.onPlacementChange}\n /> \n <Button type=\"primary\" onClick={this.onOpen}> open </Button>\n <Drawer\n title=\"标题\"\n visible={this.state.visible}\n placement={this.state.placement}\n onClose={this.onClose}>\n Start your business here by searching a popular product\n </Drawer>\n </div>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
Select width drawer
\n","order":"3"},"codes":{"jsx":"import { Radio, Drawer, Select } from '@alifd/next';\n\nconst Option = Select.Option;\n\nconst onChange = function (value) {\n console.log(value);\n};\nconst onBlur = function (e) {\n console.log(/onblur/,e);\n};\n\nconst onToggleHighlightItem = function (item, type) {\n console.log(item, type);\n};\n\nclass Demo extends React.Component {\n state = {\n placement: 'right'\n };\n\n onPlacementChange = dir => {\n this.setState({\n placement: dir\n });\n }\n\n render() {\n const drawerProps = {\n placement: this.state.placement,\n closeable: 'mask',\n bodyStyle: {padding: 0}\n };\n return (\nimport { Radio, Drawer, Select } from '@alifd/next';\n\nconst Option = Select.Option;\n\nconst onChange = function (value) {\n console.log(value);\n};\nconst onBlur = function (e) {\n console.log(/onblur/,e);\n};\n\nconst onToggleHighlightItem = function (item, type) {\n console.log(item, type);\n};\n\nclass Demo extends React.Component {\n state = {\n placement: 'right'\n };\n\n onPlacementChange = dir => {\n this.setState({\n placement: dir\n });\n }\n\n render() {\n const drawerProps = {\n placement: this.state.placement,\n closeable: 'mask',\n bodyStyle: {padding: 0}\n };\n return (\n <div>\n <Radio.Group\n dataSource={['right', 'bottom', 'left', 'top']}\n defaultValue={'right'}\n onChange={this.onPlacementChange}\n /> \n\n <Select id=\"basic-demo\" popupComponent={Drawer} popupProps={drawerProps} autoWidth={false} onChange={onChange} onBlur={onBlur} onToggleHighlightItem={onToggleHighlightItem} defaultValue=\"jack\" aria-label=\"name is\" hasClear>\n <Option value=\"jack\">Jack</Option>\n <Option value=\"frank\">Frank</Option>\n <Option value=\"hugo\">Hugo</Option>\n </Select>\n </div>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
将 Select 的弹出模式换成 Drawer
\n","order":"3"},"codes":{"jsx":"import { Radio, Drawer, Select } from '@alifd/next';\n\nconst Option = Select.Option;\n\nconst onChange = function (value) {\n console.log(value);\n};\nconst onBlur = function (e) {\n console.log(/onblur/,e);\n};\n\nconst onToggleHighlightItem = function (item, type) {\n console.log(item, type);\n};\n\nclass Demo extends React.Component {\n state = {\n placement: 'right'\n };\n\n onPlacementChange = dir => {\n this.setState({\n placement: dir\n });\n }\n\n render() {\n const drawerProps = {\n placement: this.state.placement,\n closeable: 'mask',\n bodyStyle: {padding: 0}\n };\n return (\nimport { Radio, Drawer, Select } from '@alifd/next';\n\nconst Option = Select.Option;\n\nconst onChange = function (value) {\n console.log(value);\n};\nconst onBlur = function (e) {\n console.log(/onblur/,e);\n};\n\nconst onToggleHighlightItem = function (item, type) {\n console.log(item, type);\n};\n\nclass Demo extends React.Component {\n state = {\n placement: 'right'\n };\n\n onPlacementChange = dir => {\n this.setState({\n placement: dir\n });\n }\n\n render() {\n const drawerProps = {\n placement: this.state.placement,\n closeable: 'mask',\n bodyStyle: {padding: 0}\n };\n return (\n <div>\n <Radio.Group\n dataSource={['right', 'bottom', 'left', 'top']}\n defaultValue={'right'}\n onChange={this.onPlacementChange}\n /> \n\n <Select id=\"basic-demo\" popupComponent={Drawer} popupProps={drawerProps} autoWidth={false} onChange={onChange} onBlur={onBlur} onToggleHighlightItem={onToggleHighlightItem} defaultValue=\"jack\" aria-label=\"name is\" hasClear>\n <Option value=\"jack\">Jack</Option>\n <Option value=\"frank\">Frank</Option>\n <Option value=\"hugo\">Hugo</Option>\n </Select>\n </div>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
The Drawer is used to provide the user with an auxiliary window for quickly performing a simple operation, confirming user information, or providing a feedback prompt without leaving the main path.
\nParam | \nDescripiton | \nType | \nDefault Value | \n
---|---|---|---|
trigger | \ntrigger the overlay to show or hide elements | \nReactElement | \n- | \n
triggerType | \ntrigger the overlay to show or hide operations, either 'click', 'hover', 'focus', or an array of them, such as ['hover', 'focus'] | \nString/Array | \n'hover' | \n
visible | \nwhether the overlay is visiible currently | \nBoolean | \n- | \n
animation | \nconfigure animation, support the {in: 'enter-class', out: 'leave-class' } object parameters, if set to false, do not play the animation. Refer to Animate component documentation for available animations. | \nObject/Boolean | \n{ in: 'expandInDown', out: 'expandOutUp' } | \n
hasMask | \nwhether to show the mask | \nBoolean | \nfalse | \n
closeable | \ncontrols how the dialog is closed. The value can be either a String or Boolean, where the string consists of the following values: close clicking the close button can close the dialog mask clicking the mask can close the dialog esc pressing the esc key can close the dialog such as 'close' or 'close,esc,mask' If set to true, all of the above close methods take effect If set to false, all of the above close methods will fail | \nString/Boolean | \n'esc,close' | \n
onVisibleChange | \ncallback function triggered when the ovlery is visible or hidden signatures: Function(visible: Boolean, type: String, e: Object) => void params: visible: {Boolean} whether the overlay is visible type: {String} the reason that triggers the overlay to show or hide _e_: {Object} DOM event | \nFunction | \nfunc.noop | \n
placement | \nplacement of the drawer options: 'top', 'right', 'bottom', 'left' | \nEnum | \n'right' | \n
Keyboard | \nDescripiton | \n
---|---|
esc | \npressing ESC will close dialog | \n
tab | \nfocus on any element that can be focused, the focus remains in the dialog when the dialog is displayed | \n
shift+tab | \nback focus on any element that can be focused, the focus remains in the dialog when the dialog is displayed | \n
抽屉
\n抽屉是用于在不离开主路径的情况下,提供用户快速执行简单的操作、确认用户信息或反馈提示的辅助窗口。
\n参数 | \n说明 | \n类型 | \n默认值 | \n
---|---|---|---|
width | \n宽度,仅在 placement是 left right 的时候生效 | \nNumber/String | \n- | \n
height | \n高度,仅在 placement是 top bottom 的时候生效 | \nNumber/String | \n- | \n
closeable | \n控制对话框关闭的方式,值可以为字符串或者布尔值,其中字符串是由以下值组成: close 表示点击关闭按钮可以关闭对话框 mask 表示点击遮罩区域可以关闭对话框 esc 表示按下 esc 键可以关闭对话框 如 'close' 或 'close,esc,mask' 如果设置为 true,则以上关闭方式全部生效 如果设置为 false,则以上关闭方式全部失效 | \nString/Boolean | \ntrue | \n
onClose | \n对话框关闭时触发的回调函数 签名: Function(trigger: String, event: Object) => void 参数: trigger: {String} 关闭触发行为的描述字符串 event: {Object} 关闭时事件对象 | \nFunction | \n() => {} | \n
placement | \n位于页面的位置 可选值: 'top', 'right', 'bottom', 'left' | \nEnum | \n'right' | \n
title | \n标题 | \nReactNode | \n- | \n
bodyStyle | \nbody上的样式 | \nObject | \n- | \n
visible | \n是否显示 | \nBoolean | \n- | \n
hasMask | \n是否显示遮罩 | \nBoolean | \ntrue | \n
animation | \n显示隐藏时动画的播放方式 | \nObject/Boolean | \n- | \n
键盘 | \n说明 | \n
---|---|
esc | \n按下ESC键将会关闭dialog而不触发任何的动作 | \n
tab | \n正向聚焦到任何可以被聚焦的元素, 在Dialog显示的时候,焦点始终保持在框体内 | \n
shift+tab | \n反向聚焦到任何可以被聚焦的元素,在Dialog显示的时候,焦点始终保持在框体内 | \n
Basic usage.
\n","order":"0"},"codes":{"jsx":"import { Dropdown, Menu } from '@alifd/next';\n\nconst menu = (\n \n);\n\nReactDOM.render(\nimport { Dropdown, Menu } from '@alifd/next';\n\nconst menu = (\n <Menu>\n <Menu.Item>Option 1</Menu.Item>\n <Menu.Item>Option 2</Menu.Item>\n <Menu.Item>Option 3</Menu.Item>\n <Menu.Item>Option 4</Menu.Item>\n </Menu>\n);\n\nReactDOM.render(\n <div>\n <Dropdown trigger={<button>Hello dropdown</button>} triggerType={[\"click\", \"hover\"]} afterOpen={() => console.log('after open')}>\n {menu}\n </Dropdown>\n </div>\n, mountNode);
最简单的用法。
\n","order":"0"},"codes":{"jsx":"import { Dropdown, Menu } from '@alifd/next';\n\nconst menu = (\n \n);\n\nReactDOM.render(\nimport { Dropdown, Menu } from '@alifd/next';\n\nconst menu = (\n <Menu>\n <Menu.Item>Option 1</Menu.Item>\n <Menu.Item>Option 2</Menu.Item>\n <Menu.Item>Option 3</Menu.Item>\n <Menu.Item>Option 4</Menu.Item>\n </Menu>\n);\n\nReactDOM.render(\n <div>\n <Dropdown trigger={<button>Hello dropdown</button>} triggerType={[\"click\", \"hover\"]} afterOpen={() => console.log('after open')}>\n {menu}\n </Dropdown>\n </div>\n, mountNode);
You can set visible
attribute to controll overlay display or hidden, and you should tell dropdown component what it controls by safeNode
attibute.
import { Dropdown, Menu, Button } from '@alifd/next';\n\nconst menu = (\n <Menu>\n <Menu.Item>Option 1</Menu.Item>\n <Menu.Item>Option 2</Menu.Item>\n <Menu.Item>Option 3</Menu.Item>\n <Menu.Item>Option 4</Menu.Item>\n </Menu>\n);\n\nclass App extends React.Component {\n state = {\n visible: false\n };\n\n toggleVisible = () => {\n this.setState({\n visible: !this.state.visible\n });\n };\n\n onVisibleChange = visible => {\n this.setState({\n visible\n });\n };\n\n render() {\n return (\n <div>\n <div style={{ marginBottom: '20px' }}>\n <Button onClick={this.toggleVisible} ref=\"button\">Toggle Overlay</Button>\n </div>\n <Dropdown trigger={<span>Hello dropdown</span>}\n triggerType=\"click\"\n visible={this.state.visible}\n onVisibleChange={this.onVisibleChange}\n safeNode={() => this.refs.button}>\n {menu}\n </Dropdown>\n </div>\n );\n }\n}\n\nReactDOM.render(<App/>, mountNode);
使用 visible 属性控制弹层显示或者隐藏,需要使用 safeNode 将其控制的元素告诉 dropdown 组件。
\n","order":"2"},"codes":{"jsx":"import { Dropdown, Menu, Button } from '@alifd/next';\n\nconst menu = (\n \n);\n\nclass App extends React.Component {\n state = {\n visible: false\n };\n\n toggleVisible = () => {\n this.setState({\n visible: !this.state.visible\n });\n };\n\n onVisibleChange = visible => {\n this.setState({\n visible\n });\n };\n\n render() {\n return (\nimport { Dropdown, Menu, Button } from '@alifd/next';\n\nconst menu = (\n <Menu>\n <Menu.Item>Option 1</Menu.Item>\n <Menu.Item>Option 2</Menu.Item>\n <Menu.Item>Option 3</Menu.Item>\n <Menu.Item>Option 4</Menu.Item>\n </Menu>\n);\n\nclass App extends React.Component {\n state = {\n visible: false\n };\n\n toggleVisible = () => {\n this.setState({\n visible: !this.state.visible\n });\n };\n\n onVisibleChange = visible => {\n this.setState({\n visible\n });\n };\n\n render() {\n return (\n <div>\n <div style={{ marginBottom: '20px' }}>\n <Button onClick={this.toggleVisible} ref=\"button\">Toggle Overlay</Button>\n </div>\n <Dropdown trigger={<span>Hello dropdown</span>}\n triggerType=\"click\"\n visible={this.state.visible}\n onVisibleChange={this.onVisibleChange}\n safeNode={() => this.refs.button}>\n {menu}\n </Dropdown>\n </div>\n );\n }\n}\n\nReactDOM.render(<App/>, mountNode);
You can set event type which trigger overlay by triggerType
attribute.
import { Dropdown, Menu } from '@alifd/next';\n\nconst menu = (\n <Menu>\n <Menu.Item>Option 1</Menu.Item>\n <Menu.Item>Option 2</Menu.Item>\n <Menu.Item>Option 3</Menu.Item>\n <Menu.Item>Option 4</Menu.Item>\n </Menu>\n);\n\nReactDOM.render(\n <Dropdown trigger={<a>Click me</a>} triggerType=\"click\">\n {menu}\n </Dropdown>, mountNode);
使用 triggerType 设置触发的事件类型。
\n","order":"1"},"codes":{"jsx":"import { Dropdown, Menu } from '@alifd/next';\n\nconst menu = (\n \n);\n\nReactDOM.render(\nimport { Dropdown, Menu } from '@alifd/next';\n\nconst menu = (\n <Menu>\n <Menu.Item>Option 1</Menu.Item>\n <Menu.Item>Option 2</Menu.Item>\n <Menu.Item>Option 3</Menu.Item>\n <Menu.Item>Option 4</Menu.Item>\n </Menu>\n);\n\nReactDOM.render(\n <Dropdown trigger={<a>Click me</a>} triggerType=\"click\">\n {menu}\n </Dropdown>, mountNode);
You can storage operation command with dropdown component when there are too much command. There will be a drop-down menu after you click or hover the trigger element. Then choose a command and run it.
\n<Dropdown triggerType={["click", "hover"]}>
(triggerType="focus" is deprecated). In our opinion, menu elements need to be confirmed by users before they are expanded when it comes to accessibility.\n\nDropdown component extends API of Popup component, unless special note.
\n
Param | \nDescripiton | \nType | \nDefault Value | \n
---|---|---|---|
children | \ncontent in overlay | \nReactNode | \n- | \n
visible | \noverlay display or not now | \nBoolean | \n- | \n
defaultVisible | \noverlay display or not in default situation | \nBoolean | \nfalse | \n
onVisibleChange | \ncallback function when toggle visible of overlay signatures: Function(visible: Boolean, type: String, e: Object) => void params: visible: {Boolean} overlay display or not type: {String} orign of trigger overlay toggle visible _e_: {Object} DOM Event | \nFunction | \nfunc.noop | \n
trigger | \ntrigger element | \nReactNode | \n- | \n
triggerType | \noperation type of trigger overlay toggle visible options: 'hover', 'click' | \nEnum | \n'hover' | \n
disabled | \noverlay can not toggle visible if you set disabled attribute | \nBoolean | \nfalse | \n
align | \noverlay position relative to trigger element, see details Overlay align | \nString | \n'tl bl' | \n
offset | \nextra adjustment for trigger element. e.g. [hoz, ver] means move to right ${hoz}px (to left in RTL mode), to bottom ${ver}px | \nArray | \n[0, 0] | \n
delay | \ndelay time of toggle overlay visible(unit: ms),if triggerType value is 'hover', delay time will work | \nNumber | \n200 | \n
autoFocus | \nlet element in overlay get focus or not after overlay was opened | \nBoolean | \ntrue | \n
hasMask | \ndisplay mask or not | \nBoolean | \nfalse | \n
cache | \nreserve child element or not after hidden overlay | \nBoolean | \nfalse | \n
animation | \nanimation play mode, support object value: { in: 'enter-class', out: 'leave-class' }, there is no animation if set false | \nObject/Boolean | \n{ in: 'expandInDown', out: 'expandOutUp' } | \n
KeyBoard | \nDescripiton | \n
---|---|
Up Arrow | \nin vertical mode, at the same level navigation, navigate to previous item | \n
Down Arrow | \nin vertical mode, at the same level navigation, navigate to next item | \n
Right Arrow | \nin vertical mode, open the submenu, navigate to the first item of the submenu; in horizontal mode, navigate at the same level, navigate to the next one | \n
Left Arrow | \nin vertical mode, close the submenu, navigate to the parent menu; in horizontal mode, navigate at the same level, navigate to the previous one | \n
Enter | \nopen submenu and navigate to the first item of the submenu | \n
Esc | \nclose submenu and navigate to the parent menu item | \n
当页面上的操作命令过多时,用此组件可以收纳操作元素。点击或移入触点,会出现一个下拉菜单。可在列表中进行选择,并执行相应的命令。
\n<Dropdown triggerType={["click", "hover"]}>
(请勿使用triggerType="focus")。我们认为,菜单类元素需要由用户确认后再展开才是一种无障碍友好的实践。\n\n继承 Popup 的 API,除非特别说明
\n
参数 | \n说明 | \n类型 | \n默认值 | \n
---|---|---|---|
children | \n弹层内容 | \nReactNode | \n- | \n
visible | \n弹层当前是否显示 | \nBoolean | \n- | \n
defaultVisible | \n弹层默认是否显示 | \nBoolean | \nfalse | \n
onVisibleChange | \n弹层显示或隐藏时触发的回调函数 签名: Function(visible: Boolean, type: String) => void 参数: visible: {Boolean} 弹层是否显示 type: {String} 触发弹层显示或隐藏的来源 fromContent 表示由Dropdown内容触发; fromTrigger 表示由trigger的点击触发; docClick 表示由document的点击触发 | \nFunction | \nfunc.noop | \n
trigger | \n触发弹层显示或者隐藏的元素 | \nReactNode | \n- | \n
triggerType | \n触发弹层显示或隐藏的操作类型,可以是 'click','hover',或者它们组成的数组,如 ['hover', 'click'] | \nString/Array | \n'hover' | \n
disabled | \n设置此属性,弹层无法显示或隐藏 | \nBoolean | \nfalse | \n
align | \n弹层相对于触发元素的定位, 详见 Overlay 的定位部分 | \nString | \n'tl bl' | \n
offset | \n弹层相对于trigger的定位的微调, 接收数组[hoz, ver], 表示弹层在 left / top 上的增量 e.g. [100, 100] 表示往右(RTL 模式下是往左) 、下分布偏移100px | \nArray | \n[0, 0] | \n
delay | \n弹层显示或隐藏的延时时间(以毫秒为单位),在 triggerType 被设置为 hover 时生效 | \nNumber | \n200 | \n
autoFocus | \n弹层打开时是否让其中的元素自动获取焦点 | \nBoolean | \n- | \n
hasMask | \n是否显示遮罩 | \nBoolean | \nfalse | \n
cache | \n隐藏时是否保留子节点 | \nBoolean | \nfalse | \n
animation | \n配置动画的播放方式,支持 { in: 'enter-class', out: 'leave-class' } 的对象参数,如果设置为 false,则不播放动画 | \nObject/Boolean | \n{ in: 'expandInDown', out: 'expandOutUp' } | \n
按键 | \n说明 | \n
---|---|
Up Arrow | \n垂直模式下,同级导航,导航到前一项 | \n
Down Arrow | \n垂直模式下,同级导航,导航到后一项 | \n
Right Arrow | \n垂直模式下,打开子菜单,导航到子菜单第一项;水平模式下,同级导航,导航到后一项 | \n
Left Arrow | \n垂直模式下,关闭子菜单,导航到父级菜单;水平模式下,同级导航,导航到前一项 | \n
Enter | \n打开子菜单,导航到子菜单第一项 | \n
Esc | \n关闭子菜单,导航到父级菜单 | \n
autoUnmount is true by default, and data will be deleted automatically. Field will keep data while autoUnmount is set to false.
\n","order":"6"},"codes":{"jsx":"import { Input, Button, Field } from '@alifd/next';\n\n\nclass Demo extends React.Component {\n state = {\n show: true,\n show2: true\n }\n field = new Field(this);\n field2 = new Field(this, { autoUnmount: false });\n\n render() {\n return (\nimport { Input, Button, Field } from '@alifd/next';\n\n\nclass Demo extends React.Component {\n state = {\n show: true,\n show2: true\n }\n field = new Field(this);\n field2 = new Field(this, { autoUnmount: false });\n\n render() {\n return (\n <div>\n {this.state.show ? < Input {...this.field.init('name', { initValue: 'autoUnmount = true' })} /> : null}\n <Button\n onClick={() => {\n console.log('value auto delete', this.field.getValues());\n }}\n style={{marginLeft: 4}}\n >\n print\n </Button>\n <Button\n onClick={() => this.setState({ show: false })}\n warning\n style={{marginLeft: 4}}\n >\n delete\n </Button>\n <br />\n <br />\n {this.state.show2 ? < Input {...this.field2.init('name2', { initValue: 'autoUnmount = false' })} /> : null}\n <Button\n onClick={() => {\n console.log('value always exist', this.field2.getValues());\n }}\n style={{marginLeft: 4}}\n >\n print\n </Button>\n <Button\n onClick={() => this.setState({ show2: false })}\n warning\n style={{marginLeft: 4}}\n >\n delete\n </Button>\n </div>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
autoUnmount 默认为 true,当组件被 unmount 的时候会自动删除数据. autoUnmount 设置为 false 后,会一直保存数据.
\n","order":"6"},"codes":{"jsx":"import { Input, Button, Field } from '@alifd/next';\n\n\nclass Demo extends React.Component {\n state = {\n show: true,\n show2: true\n }\n field = new Field(this);\n field2 = new Field(this, { autoUnmount: false });\n\n render() {\n return (\nimport { Input, Button, Field } from '@alifd/next';\n\n\nclass Demo extends React.Component {\n state = {\n show: true,\n show2: true\n }\n field = new Field(this);\n field2 = new Field(this, { autoUnmount: false });\n\n render() {\n return (\n <div>\n {this.state.show ? < Input {...this.field.init('name', { initValue: 'autoUnmount = true' })} /> : null}\n <Button\n onClick={() => {\n console.log('value auto delete', this.field.getValues());\n }}\n style={{marginLeft: 4}}\n >\n print\n </Button>\n <Button\n onClick={() => this.setState({ show: false })}\n warning\n style={{marginLeft: 4}}\n >\n delete\n </Button>\n <br />\n <br />\n {this.state.show2 ? < Input {...this.field2.init('name2', { initValue: 'autoUnmount = false' })} /> : null}\n <Button\n onClick={() => {\n console.log('value always exist', this.field2.getValues());\n }}\n style={{marginLeft: 4}}\n >\n print\n </Button>\n <Button\n onClick={() => this.setState({ show2: false })}\n warning\n style={{marginLeft: 4}}\n >\n delete\n </Button>\n </div>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
usage of getValue
setValue
reset
import { Input, Button, Field } from '@alifd/next';\n\n\n\nclass App extends React.Component {\n field = new Field(this);\n\n onGetValue() {\n console.log(this.field.getValue('input'));\n }\n\n render() {\n const { init, setValue, reset } = this.field;\n\n return (<div className=\"demo\">\n <Input {...init('input', {initValue: 'test'})} />\n <br/><br/>\n <Button type=\"primary\" onClick={this.onGetValue.bind(this)}>getValue</Button>\n <Button type=\"primary\" onClick={() => setValue('input', 'set me by click')}>setValue</Button>\n <Button onClick={() => reset()}>reset</Button>\n </div>);\n }\n}\n\n\nReactDOM.render(<App/>, mountNode);\n
.demo .next-btn {\n margin-right: 5px;\n}
getValue
setValue
reset
的使用
import { Input, Button, Field } from '@alifd/next';\n\n\n\nclass App extends React.Component {\n field = new Field(this);\n\n onGetValue() {\n console.log(this.field.getValue('input'));\n }\n\n render() {\n const { init, setValue, reset } = this.field;\n\n return (<div className=\"demo\">\n <Input {...init('input', {initValue: 'test'})} />\n <br/><br/>\n <Button type=\"primary\" onClick={this.onGetValue.bind(this)}>getValue</Button>\n <Button type=\"primary\" onClick={() => setValue('input', 'set me by click')}>setValue</Button>\n <Button onClick={() => reset()}>reset</Button>\n </div>);\n }\n}\n\n\nReactDOM.render(<App/>, mountNode);\n
.demo .next-btn {\n margin-right: 5px;\n}
must
: has api of onChange
, so you can use getValue
but you can't setValue
\nperfect support
: has api of value
onChange
. value: set data for component; onChange: return first param for component
import { Button, Field } from '@alifd/next';\n\n\nclass Custom extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n value: typeof props.value === 'undefined' ? [] : props.value\n };\n }\n\n // update value\n componentWillReceiveProps(nextProps) {\n if ('value' in nextProps) {\n this.setState({\n value: typeof nextProps.value === 'undefined' ? [] : nextProps.value\n });\n }\n }\n\n onAdd = () => {\n const value = this.state.value.concat([]);\n value.push('new');\n\n this.setState({\n value\n });\n this.props.onChange(value);\n }\n\n render() {\n return (<div className=\"custom\">\n {this.state.value.map((v, i) => {\n return <Button key={i} >{v}</Button>;\n })}\n <Button type=\"primary\" onClick={this.onAdd.bind(this)}>Add + </Button>\n </div>);\n }\n}\n\n/* eslint-disable react/no-multi-comp */\nclass App extends React.Component {\n field = new Field(this, {\n deepReset: true\n });\n\n onGetValue() {\n console.log(this.field.getValue('custom'));\n }\n\n render() {\n const { init, setValue, reset } = this.field;\n\n return (<div className=\"demo\">\n <Custom {...init('custom', {initValue: ['test']})} />\n\n <br/><br/>\n\n <Button type=\"primary\" onClick={this.onGetValue.bind(this)}>getValue</Button>\n <Button type=\"primary\" onClick={() => setValue('custom', ['test', 'setValue'])}>setValue</Button>\n <Button onClick={() => reset()}>reset</Button>\n </div>);\n }\n}\nReactDOM.render(<App/>, mountNode);
.demo .next-btn {\n margin-right: 5px;\n}\n.custom {\n border: 1px dashed;\n padding: 4px;\n display: inline-block;\n}\n.custom span {\n border: 1px solid green;\n padding: 0px 5px;\n height: 24px;\n display: inline-block;\n margin-right: 2px;\n}
自己的组件如何接入Field。
\n最低标准
: 组件支持 onChange
读取组件数据。达到效果
:Field 可以 getValue,但是 setValue 无效
完全支持
: 组件支持受控, 也就是支持两个api:value
onChange
. value: 设置组件的数据; onChange: 在组件修改的时候在第一个数暴露数据
import { Button, Field } from '@alifd/next';\n\n\nclass Custom extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n value: typeof props.value === 'undefined' ? [] : props.value\n };\n }\n\n // update value\n componentWillReceiveProps(nextProps) {\n if ('value' in nextProps) {\n this.setState({\n value: typeof nextProps.value === 'undefined' ? [] : nextProps.value\n });\n }\n }\n\n onAdd = () => {\n const value = this.state.value.concat([]);\n value.push('new');\n\n this.setState({\n value\n });\n this.props.onChange(value);\n }\n\n render() {\n return (<div className=\"custom\">\n {this.state.value.map((v, i) => {\n return <Button key={i} >{v}</Button>;\n })}\n <Button type=\"primary\" onClick={this.onAdd.bind(this)}>Add + </Button>\n </div>);\n }\n}\n\n/* eslint-disable react/no-multi-comp */\nclass App extends React.Component {\n field = new Field(this, {\n deepReset: true\n });\n\n onGetValue() {\n console.log(this.field.getValue('custom'));\n }\n\n render() {\n const { init, setValue, reset } = this.field;\n\n return (<div className=\"demo\">\n <Custom {...init('custom', {initValue: ['test']})} />\n\n <br/><br/>\n\n <Button type=\"primary\" onClick={this.onGetValue.bind(this)}>getValue</Button>\n <Button type=\"primary\" onClick={() => setValue('custom', ['test', 'setValue'])}>setValue</Button>\n <Button onClick={() => reset()}>reset</Button>\n </div>);\n }\n}\nReactDOM.render(<App/>, mountNode);
.demo .next-btn {\n margin-right: 5px;\n}\n.custom {\n border: 1px dashed;\n padding: 4px;\n display: inline-block;\n}\n.custom span {\n border: 1px solid green;\n padding: 0px 5px;\n height: 24px;\n display: inline-block;\n margin-right: 2px;\n}
by use deleteArrayValue/addArrayValue
could delete and add array , and fix keys offset problem
{JSON.stringify(dataSource, null, 2)}\n
{JSON.stringify(dataSource, null, 2)}\n
import { Button, Input, Table, Field } from '@alifd/next';\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.idx = 3;\n\n this.field = new Field(this, {\n parseName: true,\n values: {\n name: [0, 1, 2, 3].map(i => {\n return { id: i, input: i };\n })\n }\n });\n }\n\n getValues = () => {\n const values = this.field.getValues();\n console.log(values);\n }\n\n addItem(index){\n ++this.idx;\n this.field.addArrayValue('name', index, {id: this.idx, input: this.idx});\n }\n\n removeItem(index) {\n this.field.deleteArrayValue('name', index);\n }\n\n input = (value, index) => <Input {...this.field.init(`name.${index}.input`)} />;\n op = (value, index) => {\n return (<span>\n <Button type=\"primary\" onClick={this.addItem.bind(this, index + 1)}>add</Button>\n <Button warning onClick={this.removeItem.bind(this, index)} style={{marginLeft: 4}}>delete</Button>\n </span>);\n }\n\n render() {\n const dataSource = this.field.getValue('name');\n return (\n <div>\n <Table dataSource={dataSource}>\n <Table.Column title=\"id\" dataIndex=\"id\" />\n <Table.Column title=\"input\" dataIndex=\"id\" cell={this.input} />\n <Table.Column title=\"operation\" cell={this.op} width={150} />\n </Table>\n <pre style={{marginTop: 8}}>{JSON.stringify(dataSource, null, 2)}</pre>\n </div>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
通过 deleteArrayValue/addArrayValue
可以往数组格式的数据里面 删除/添加 数据, 并且自动订正其他 name 的 偏移问题
{JSON.stringify(dataSource, null, 2)}\n
{JSON.stringify(dataSource, null, 2)}\n
import { Button, Input, Table, Field } from '@alifd/next';\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.idx = 3;\n\n this.field = new Field(this, {\n parseName: true,\n values: {\n name: [0, 1, 2, 3].map(i => {\n return { id: i, input: i };\n })\n }\n });\n }\n\n getValues = () => {\n const values = this.field.getValues();\n console.log(values);\n }\n\n addItem(index){\n ++this.idx;\n this.field.addArrayValue('name', index, {id: this.idx, input: this.idx});\n }\n\n removeItem(index) {\n this.field.deleteArrayValue('name', index);\n }\n\n input = (value, index) => <Input {...this.field.init(`name.${index}.input`)} />;\n op = (value, index) => {\n return (<span>\n <Button type=\"primary\" onClick={this.addItem.bind(this, index + 1)}>add</Button>\n <Button warning onClick={this.removeItem.bind(this, index)} style={{marginLeft: 4}}>delete</Button>\n </span>);\n }\n\n render() {\n const dataSource = this.field.getValue('name');\n return (\n <div>\n <Table dataSource={dataSource}>\n <Table.Column title=\"id\" dataIndex=\"id\" />\n <Table.Column title=\"input\" dataIndex=\"id\" cell={this.input} />\n <Table.Column title=\"operation\" cell={this.op} width={150} />\n </Table>\n <pre style={{marginTop: 8}}>{JSON.stringify(dataSource, null, 2)}</pre>\n </div>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
Field
exposes a React Hook useField
as a static method. Takes in the options
parameter used with new Field(...)
. dependencies: react@^16.8
import ReactDOM from 'react-dom';\nimport React from 'react';\nimport { Input, Button, Field } from '@alifd/next';\n\n\nfunction App() {\n const field = Field.useField();\n\n const { init, setValue, reset, getError } = field;\n\n function onGetValue() {\n console.log(field.getValue('input'));\n }\n\n function onSetValue() {\n field.setValue('input', 'xyz');\n }\n\n return (<div className=\"demo\">\n <Input {...init('input', {\n initValue: 'test', \n rules: [{\n required: true,\n pattern: /hello/,\n message: 'must be hello'\n }]\n })} />\n <span style={{color: 'red'}}>{getError('input')}</span>\n\n <br/><br/>\n <Button onClick={onSetValue}> setValue </Button>\n <Button onClick={onGetValue}> getValue </Button>\n <br/><br/>\n </div>);\n}\n\n\nReactDOM.render(<App/>, mountNode);\n
在 functional component 里可使用 Field.useField
支持 hooks. 依赖: react@^16.8
import ReactDOM from 'react-dom';\nimport React from 'react';\nimport { Input, Button, Field } from '@alifd/next';\n\n\nfunction App() {\n const field = Field.useField();\n\n const { init, setValue, reset, getError } = field;\n\n function onGetValue() {\n console.log(field.getValue('input'));\n }\n\n function onSetValue() {\n field.setValue('input', 'xyz');\n }\n\n return (<div className=\"demo\">\n <Input {...init('input', {\n initValue: 'test', \n rules: [{\n required: true,\n pattern: /hello/,\n message: 'must be hello'\n }]\n })} />\n <span style={{color: 'red'}}>{getError('input')}</span>\n\n <br/><br/>\n <Button onClick={onSetValue}> setValue </Button>\n <Button onClick={onGetValue}> getValue </Button>\n <br/><br/>\n </div>);\n}\n\n\nReactDOM.render(<App/>, mountNode);\n
multi type of component
\n","order":"8"},"codes":{"jsx":"import { Button, Checkbox, Input, Radio, Select, Range, DatePicker, TimePicker, Field } from '@alifd/next';\n\n\nconst CheckboxGroup = Checkbox.Group;\nconst RadioGroup = Radio.Group;\n\nconst list = [\n {\n value: 'apple',\n label: 'apple'\n }, {\n value: 'pear',\n label: 'pear'\n }, {\n value: 'orange',\n label: 'orange'\n }\n];\nconst layout = {\n marginBottom: 10,\n width: 400\n};\n\nclass App extends React.Component {\n field = new Field(this);\n\n render() {\n const {init, getValue} = this.field;\n\n return (import { Button, Checkbox, Input, Radio, Select, Range, DatePicker, TimePicker, Field } from '@alifd/next';\n\n\nconst CheckboxGroup = Checkbox.Group;\nconst RadioGroup = Radio.Group;\n\nconst list = [\n {\n value: 'apple',\n label: 'apple'\n }, {\n value: 'pear',\n label: 'pear'\n }, {\n value: 'orange',\n label: 'orange'\n }\n];\nconst layout = {\n marginBottom: 10,\n width: 400\n};\n\nclass App extends React.Component {\n field = new Field(this);\n\n render() {\n const {init, getValue} = this.field;\n\n return (<div className=\"demo\">\n <div style={{marginBottom: 10}}>\n <RadioGroup {...init('radiogroup', {initValue: 'a'})} >\n <Radio value=\"a\">A</Radio>\n <Radio value=\"b\">B</Radio>\n <Radio value=\"c\">C</Radio>\n <Radio value=\"d\">D</Radio>\n </RadioGroup>\n </div>\n\n {\n getValue('radiogroup') !== 'd' ?\n <Select {...init('name', {initValue: 'lucy'})} style={layout}>\n <Select.Option value=\"jack\">jack</Select.Option>\n <Select.Option value=\"lucy\">lucy</Select.Option>\n <Select.Option value=\"disabled\" disabled>disabled</Select.Option>\n <Select.Option value=\"hugohua\">hugohua</Select.Option>\n </Select> :\n <Input {...init('name', {initValue: 'frankqian'})} />\n }\n <br/>\n\n <Range style={{...layout, marginTop: 30}} slider={'double'} scales={10}\n marks={10} {...init('range', {initValue: [20, 40]})}/>\n\n <div style={{marginBottom: 10}}>\n <CheckboxGroup dataSource={list} {...init('checkboxgroup', {initValue: ['apple']})} />\n </div>\n <div style={{marginBottom: 10}}>\n <DatePicker {...init('datepicker')}/>\n </div>\n <div style={{marginBottom: 10}}>\n <DatePicker.RangePicker {...init('rangepicker')}/>\n </div>\n <div style={{marginBottom: 10}}>\n <TimePicker {...init('timepicker')}/>\n </div>\n <Button type=\"primary\" onClick={() => {\n console.log(this.field.getValues());\n }}>getValues</Button>\n <Button onClick={() => {\n this.field.setValues({\n name: 'hugohua',\n range: [30, 50],\n checkboxgroup: ['orange'],\n radiogroup: 'd'\n });\n }}>setValues</Button>\n <Button onClick={() => {\n this.field.reset();\n }}>reset</Button>\n </div>);\n }\n}\n\n\nReactDOM.render(<App/>, mountNode);\n
.demo .next-btn {\n margin-right: 5px;\n}
多组件混合使用
\n","order":"8"},"codes":{"jsx":"import { Button, Checkbox, Input, Radio, Select, Range, DatePicker, TimePicker, Field } from '@alifd/next';\n\n\nconst CheckboxGroup = Checkbox.Group;\nconst RadioGroup = Radio.Group;\n\nconst list = [\n {\n value: 'apple',\n label: 'apple'\n }, {\n value: 'pear',\n label: 'pear'\n }, {\n value: 'orange',\n label: 'orange'\n }\n];\nconst layout = {\n marginBottom: 10,\n width: 400\n};\n\nclass App extends React.Component {\n field = new Field(this);\n\n render() {\n const {init, getValue} = this.field;\n\n return (import { Button, Checkbox, Input, Radio, Select, Range, DatePicker, TimePicker, Field } from '@alifd/next';\n\n\nconst CheckboxGroup = Checkbox.Group;\nconst RadioGroup = Radio.Group;\n\nconst list = [\n {\n value: 'apple',\n label: 'apple'\n }, {\n value: 'pear',\n label: 'pear'\n }, {\n value: 'orange',\n label: 'orange'\n }\n];\nconst layout = {\n marginBottom: 10,\n width: 400\n};\n\nclass App extends React.Component {\n field = new Field(this);\n\n render() {\n const {init, getValue} = this.field;\n\n return (<div className=\"demo\">\n <div style={{marginBottom: 10}}>\n <RadioGroup {...init('radiogroup', {initValue: 'a'})} >\n <Radio value=\"a\">A</Radio>\n <Radio value=\"b\">B</Radio>\n <Radio value=\"c\">C</Radio>\n <Radio value=\"d\">D</Radio>\n </RadioGroup>\n </div>\n\n {\n getValue('radiogroup') !== 'd' ?\n <Select {...init('name', {initValue: 'lucy'})} style={layout}>\n <Select.Option value=\"jack\">jack</Select.Option>\n <Select.Option value=\"lucy\">lucy</Select.Option>\n <Select.Option value=\"disabled\" disabled>disabled</Select.Option>\n <Select.Option value=\"hugohua\">hugohua</Select.Option>\n </Select> :\n <Input {...init('name', {initValue: 'frankqian'})} />\n }\n <br/>\n\n <Range style={{...layout, marginTop: 30}} slider={'double'} scales={10}\n marks={10} {...init('range', {initValue: [20, 40]})}/>\n\n <div style={{marginBottom: 10}}>\n <CheckboxGroup dataSource={list} {...init('checkboxgroup', {initValue: ['apple']})} />\n </div>\n <div style={{marginBottom: 10}}>\n <DatePicker {...init('datepicker')}/>\n </div>\n <div style={{marginBottom: 10}}>\n <DatePicker.RangePicker {...init('rangepicker')}/>\n </div>\n <div style={{marginBottom: 10}}>\n <TimePicker {...init('timepicker')}/>\n </div>\n <Button type=\"primary\" onClick={() => {\n console.log(this.field.getValues());\n }}>getValues</Button>\n <Button onClick={() => {\n this.field.setValues({\n name: 'hugohua',\n range: [30, 50],\n checkboxgroup: ['orange'],\n radiogroup: 'd'\n });\n }}>setValues</Button>\n <Button onClick={() => {\n this.field.reset();\n }}>reset</Button>\n </div>);\n }\n}\n\n\nReactDOM.render(<App/>, mountNode);\n
.demo .next-btn {\n margin-right: 5px;\n}
custom value
by api getValueFromEvent
import { Button, Input, Field } from '@alifd/next';\n\n\nclass App extends React.Component {\n\n field = new Field(this);\n\n normFile(list) {\n if (Array.isArray(list)) {\n return list;\n }\n return list && list.fileList;\n }\n\n normDate(date, strdate) {\n console.log('normDate:', date, strdate);\n return strdate;\n }\n\n render() {\n const init = this.field.init;\n\n return (<div>\n <Input {...init('name', { getValueFromEvent: (value) => {\n if (value.match(/##/)) {\n return value;\n } else {\n return `## title-${value}`;\n }\n }})} />\n <Button type=\"primary\" onClick={() => {\n console.log(this.field.getValues());\n }}>getValues</Button>\n </div>);\n }\n}\n\n\nReactDOM.render(<App/>, mountNode);
通过 getValueFromEvent
自定义从组件的 Event
获取 value
的方式
import { Button, Input, Field } from '@alifd/next';\n\n\nclass App extends React.Component {\n\n field = new Field(this);\n\n normFile(list) {\n if (Array.isArray(list)) {\n return list;\n }\n return list && list.fileList;\n }\n\n normDate(date, strdate) {\n console.log('normDate:', date, strdate);\n return strdate;\n }\n\n render() {\n const init = this.field.init;\n\n return (<div>\n <Input {...init('name', { getValueFromEvent: (value) => {\n if (value.match(/##/)) {\n return value;\n } else {\n return `## title-${value}`;\n }\n }})} />\n <Button type=\"primary\" onClick={() => {\n console.log(this.field.getValues());\n }}>getValues</Button>\n </div>);\n }\n}\n\n\nReactDOM.render(<App/>, mountNode);
manage value by onChange
import { Input, Select, Range, Field } from '@alifd/next';\n\n\n\nclass App extends React.Component {\n field = new Field(this, {\n onChange: (name, value) => {\n console.log(this.field.getValues());\n\n switch (name) {\n case 'input':\n this.field.setValue('sync', `change to: ${value}`);\n break;\n case 'select':\n this.field.setValue('sync', `${value} is coming`);\n break;\n case 'range':\n this.field.setValue('sync', ` (${value.join(',')}) ready`);\n break;\n }\n }\n });\n\n render() {\n const {init, getValue} = this.field;\n const layout = {\n marginBottom: 10,\n width: 400\n };\n\n return (<div>\n <Input placeholder=\"controlled by onChange\" {...init('input')} style={layout}/><br/>\n <Input placeholder=\"under control\" {...init('input')} style={layout}/><br/>\n\n <Select style={layout} {...init('select', {initValue: 'lucy'})}>\n <Select.Option value=\"jack\">jack</Select.Option>\n <Select.Option value=\"lucy\">lucy</Select.Option>\n <Select.Option value=\"disabled\" disabled>disabled</Select.Option>\n <Select.Option value=\"hugo\">hugo</Select.Option>\n </Select><br/>\n\n {\n getValue('select') !== 'hugo' ?\n <Range\n style={{...layout, marginTop: 30}}\n slider={'double'} scales={10} marks={10}\n {...init('range', {initValue: [20, 40], trigger: 'onProcess'})}\n /> : null\n }\n <br/>\n\n <hr style={{marginBottom: 10}}/>\n <Input placeholder=\"everyone can control me\" {...init('sync')} style={layout}/><br/>\n </div>);\n }\n}\n\nReactDOM.render(<App/>, mountNode);
组件之间的关联控制. onChange
统一管理。
import { Input, Select, Range, Field } from '@alifd/next';\n\n\n\nclass App extends React.Component {\n field = new Field(this, {\n onChange: (name, value) => {\n console.log(this.field.getValues());\n\n switch (name) {\n case 'input':\n this.field.setValue('sync', `change to: ${value}`);\n break;\n case 'select':\n this.field.setValue('sync', `${value} is coming`);\n break;\n case 'range':\n this.field.setValue('sync', ` (${value.join(',')}) ready`);\n break;\n }\n }\n });\n\n render() {\n const {init, getValue} = this.field;\n const layout = {\n marginBottom: 10,\n width: 400\n };\n\n return (<div>\n <Input placeholder=\"controlled by onChange\" {...init('input')} style={layout}/><br/>\n <Input placeholder=\"under control\" {...init('input')} style={layout}/><br/>\n\n <Select style={layout} {...init('select', {initValue: 'lucy'})}>\n <Select.Option value=\"jack\">jack</Select.Option>\n <Select.Option value=\"lucy\">lucy</Select.Option>\n <Select.Option value=\"disabled\" disabled>disabled</Select.Option>\n <Select.Option value=\"hugo\">hugo</Select.Option>\n </Select><br/>\n\n {\n getValue('select') !== 'hugo' ?\n <Range\n style={{...layout, marginTop: 30}}\n slider={'double'} scales={10} marks={10}\n {...init('range', {initValue: [20, 40], trigger: 'onProcess'})}\n /> : null\n }\n <br/>\n\n <hr style={{marginBottom: 10}}/>\n <Input placeholder=\"everyone can control me\" {...init('sync')} style={layout}/><br/>\n </div>);\n }\n}\n\nReactDOM.render(<App/>, mountNode);
set value in componentWillReceiveProps
email: {this.props.email}
\n \nemail: {this.props.email}
\n \nimport { Input, Button, Field } from '@alifd/next';\n\n\nimport { combineReducers, createStore } from 'redux';\nimport { Provider, connect } from 'react-redux';\n\nfunction formReducer(state = {email: 'frankqian@qq.com'}, action) {\n switch (action.type) {\n case 'save_fields':\n return {\n ...state,\n ...action.payload\n };\n default:\n return state;\n }\n}\n\nclass Demo extends React.Component {\n componentWillReceiveProps(nextProps) {\n this.field.setValues({\n email: nextProps.email,\n newlen: nextProps.email.length\n });\n }\n\n field = new Field(this, {\n onChange: (name, value) => {\n console.log('onChange', name, value);\n this.field.setValue('newlen', value.length);\n this.props.dispatch({\n type: 'save_fields',\n payload: {\n [name]: value\n }\n });\n }\n });\n\n setEmail() {\n this.props.dispatch({\n type: 'save_fields',\n payload: {\n email: 'qq@gmail.com'\n }\n });\n }\n\n\n render() {\n const init = this.field.init;\n\n const newLen = init('newlen', { initValue: this.props.email.length });\n\n return (<div>\n <Input {...init('email', { initValue: this.props.email }, {\n rules: [\n {required: true, type: 'email', message: 'at least 5 chars'}\n ]\n })} />\n now length is:{newLen.value}\n <p>email: {this.props.email}</p>\n <Button onClick={this.setEmail.bind(this)}>set</Button>\n </div>);\n }\n}\n\n\nconst ReduxDemo = connect((state) => {\n return {\n email: state.formReducer.email\n };\n})(Demo);\n\n\nconst store = createStore(combineReducers({\n formReducer\n}));\n\nReactDOM.render((<Provider store={store}>\n <div>\n <ReduxDemo />\n </div>\n</Provider>), mountNode);
在 redux 中使用, 在 componentWillReceiveProps
更新
email: {this.props.email}
\n \nemail: {this.props.email}
\n \nimport { Input, Button, Field } from '@alifd/next';\n\n\nimport { combineReducers, createStore } from 'redux';\nimport { Provider, connect } from 'react-redux';\n\nfunction formReducer(state = {email: 'frankqian@qq.com'}, action) {\n switch (action.type) {\n case 'save_fields':\n return {\n ...state,\n ...action.payload\n };\n default:\n return state;\n }\n}\n\nclass Demo extends React.Component {\n componentWillReceiveProps(nextProps) {\n this.field.setValues({\n email: nextProps.email,\n newlen: nextProps.email.length\n });\n }\n\n field = new Field(this, {\n onChange: (name, value) => {\n console.log('onChange', name, value);\n this.field.setValue('newlen', value.length);\n this.props.dispatch({\n type: 'save_fields',\n payload: {\n [name]: value\n }\n });\n }\n });\n\n setEmail() {\n this.props.dispatch({\n type: 'save_fields',\n payload: {\n email: 'qq@gmail.com'\n }\n });\n }\n\n\n render() {\n const init = this.field.init;\n\n const newLen = init('newlen', { initValue: this.props.email.length });\n\n return (<div>\n <Input {...init('email', { initValue: this.props.email }, {\n rules: [\n {required: true, type: 'email', message: 'at least 5 chars'}\n ]\n })} />\n now length is:{newLen.value}\n <p>email: {this.props.email}</p>\n <Button onClick={this.setEmail.bind(this)}>set</Button>\n </div>);\n }\n}\n\n\nconst ReduxDemo = connect((state) => {\n return {\n email: state.formReducer.email\n };\n})(Demo);\n\n\nconst store = createStore(combineReducers({\n formReducer\n}));\n\nReactDOM.render((<Provider store={store}>\n <div>\n <ReduxDemo />\n </div>\n</Provider>), mountNode);
set errors of component by yourself
\n","order":"3"},"codes":{"jsx":"import { Input, Button, Field } from '@alifd/next';\n\n\n\nclass App extends React.Component {\n field = new Field(this);\n\n validate = () => {\n console.log(this.field.getErrors());\n this.field.validate((error, values) => {\n // eslint-disable-next-line no-alert\n alert(JSON.stringify(error));\n });\n };\n\n render() {\n const { init, getError, setError, setErrors } = this.field;\n return (import { Input, Button, Field } from '@alifd/next';\n\n\n\nclass App extends React.Component {\n field = new Field(this);\n\n validate = () => {\n console.log(this.field.getErrors());\n this.field.validate((error, values) => {\n // eslint-disable-next-line no-alert\n alert(JSON.stringify(error));\n });\n };\n\n render() {\n const { init, getError, setError, setErrors } = this.field;\n return (<div className=\"demo\">\n <Input {...init('input', {\n rules: [{\n required: true,\n pattern: /hello/,\n message: 'must be hello'\n }]\n })} /><br/>\n <span style={{color: 'red'}}>{getError('input')}</span>\n\n <br/>\n <Button onClick={() => {\n setError('input', 'set error 1');\n }}>setError</Button>\n\n <Button onClick={() => {\n setErrors({input: 'set error 2'});\n }}>setErrors</Button>\n\n <Button onClick={() => {\n setErrors({input: ''});\n }}>clear</Button>\n\n <br/><br/>\n <Input {...init('input2')} /><br/>\n <span style={{color: 'red'}}>{getError('input2')}</span><br/>\n\n <Button onClick={() => {\n setError('input2', 'errors will be removed by onChange and shown on validate');\n }}>setError</Button>\n\n <Button onClick={this.validate}>\n validate</Button> \n </div>);\n }\n}\n\n\nReactDOM.render(<App/>, mountNode);\n\n
.demo .next-btn {\n margin-right: 5px;\n}
自己控制组件的errors
\n","order":"3"},"codes":{"jsx":"import { Input, Button, Field } from '@alifd/next';\n\n\n\nclass App extends React.Component {\n field = new Field(this);\n\n validate = () => {\n console.log(this.field.getErrors());\n this.field.validate((error, values) => {\n // eslint-disable-next-line no-alert\n alert(JSON.stringify(error));\n });\n };\n\n render() {\n const { init, getError, setError, setErrors } = this.field;\n return (import { Input, Button, Field } from '@alifd/next';\n\n\n\nclass App extends React.Component {\n field = new Field(this);\n\n validate = () => {\n console.log(this.field.getErrors());\n this.field.validate((error, values) => {\n // eslint-disable-next-line no-alert\n alert(JSON.stringify(error));\n });\n };\n\n render() {\n const { init, getError, setError, setErrors } = this.field;\n return (<div className=\"demo\">\n <Input {...init('input', {\n rules: [{\n required: true,\n pattern: /hello/,\n message: 'must be hello'\n }]\n })} /><br/>\n <span style={{color: 'red'}}>{getError('input')}</span>\n\n <br/>\n <Button onClick={() => {\n setError('input', 'set error 1');\n }}>setError</Button>\n\n <Button onClick={() => {\n setErrors({input: 'set error 2'});\n }}>setErrors</Button>\n\n <Button onClick={() => {\n setErrors({input: ''});\n }}>clear</Button>\n\n <br/><br/>\n <Input {...init('input2')} /><br/>\n <span style={{color: 'red'}}>{getError('input2')}</span><br/>\n\n <Button onClick={() => {\n setError('input2', 'errors will be removed by onChange and shown on validate');\n }}>setError</Button>\n\n <Button onClick={this.validate}>\n validate</Button> \n </div>);\n }\n}\n\n\nReactDOM.render(<App/>, mountNode);\n\n
.demo .next-btn {\n margin-right: 5px;\n}
from init('obj.b')
to obj={obj:{b:'value'}}
;
from init('arr.0')
to obj={arr:['']}
;
{JSON.stringify(this.field.getValues(), null, 2)}\n\n
{JSON.stringify(this.field.getValues(), null, 2)}\n\n
import { Input, Button, Field } from '@alifd/next';\n\n\n\nclass App extends React.Component {\n field = new Field(this, {\n parseName: true,\n values: {\n objWithDefaults: {\n a: 1,\n b: 2\n }\n }\n });\n\n onGetValue() {\n console.log(this.field.getValues());\n }\n\n onSetValue() {\n this.field.setValues({\n obj: {\n b: 'b',\n c: 'c'\n },\n arr: ['first', 'second'],\n objWithDefaults: {\n a: 100,\n b: 200\n }\n });\n }\n\n render() {\n const { init, reset, resetToDefault } = this.field;\n\n return (<div className=\"demo\">\n <h3>Object transfer</h3>\n obj.b: <Input {...init('obj.b', {initValue: 'test1'})} /> \n obj.c: <Input {...init('obj.c', {initValue: 'test2'})} />\n\n <br/>\n\n <h3>Array transfer</h3>\n arr.0: <Input {...init('arr.0', {initValue: '0'})} /> \n arr.1: <Input {...init('arr.1', {initValue: '1'})} />\n <br/><br/>\n\n <h3>Object with Defaults</h3>\n objWithDefaults.a: <Input {...init('objWithDefaults.a')} /> \n objWithDefaults.b: <Input {...init('objWithDefaults.b')} />\n <br/><br/>\n\n result:\n <pre>{JSON.stringify(this.field.getValues(), null, 2)}</pre>\n\n <br/><br/>\n\n <Button type=\"primary\" onClick={this.onGetValue.bind(this)}>getValues</Button>\n <Button onClick={this.onSetValue.bind(this)}>setValues</Button>\n <Button onClick={() => reset()}>reset</Button>\n <Button onClick={() => resetToDefault()}>resetToDefault</Button>\n </div>);\n }\n}\n\n\nReactDOM.render(<App/>, mountNode);
.demo .next-btn {\n margin-right: 5px;\n}
把 init('obj.b')
的数据转换成 obj={obj:{b:'value'}}
;
把 init('arr.0')
的数据转换成 obj={arr:['']}
;
{JSON.stringify(this.field.getValues(), null, 2)}\n\n
{JSON.stringify(this.field.getValues(), null, 2)}\n\n
import { Input, Button, Field } from '@alifd/next';\n\n\n\nclass App extends React.Component {\n field = new Field(this, {\n parseName: true,\n values: {\n objWithDefaults: {\n a: 1,\n b: 2\n }\n }\n });\n\n onGetValue() {\n console.log(this.field.getValues());\n }\n\n onSetValue() {\n this.field.setValues({\n obj: {\n b: 'b',\n c: 'c'\n },\n arr: ['first', 'second'],\n objWithDefaults: {\n a: 100,\n b: 200\n }\n });\n }\n\n render() {\n const { init, reset, resetToDefault } = this.field;\n\n return (<div className=\"demo\">\n <h3>Object transfer</h3>\n obj.b: <Input {...init('obj.b', {initValue: 'test1'})} /> \n obj.c: <Input {...init('obj.c', {initValue: 'test2'})} />\n\n <br/>\n\n <h3>Array transfer</h3>\n arr.0: <Input {...init('arr.0', {initValue: '0'})} /> \n arr.1: <Input {...init('arr.1', {initValue: '1'})} />\n <br/><br/>\n\n <h3>Object with Defaults</h3>\n objWithDefaults.a: <Input {...init('objWithDefaults.a')} /> \n objWithDefaults.b: <Input {...init('objWithDefaults.b')} />\n <br/><br/>\n\n result:\n <pre>{JSON.stringify(this.field.getValues(), null, 2)}</pre>\n\n <br/><br/>\n\n <Button type=\"primary\" onClick={this.onGetValue.bind(this)}>getValues</Button>\n <Button onClick={this.onSetValue.bind(this)}>setValues</Button>\n <Button onClick={() => reset()}>reset</Button>\n <Button onClick={() => resetToDefault()}>resetToDefault</Button>\n </div>);\n }\n}\n\n\nReactDOM.render(<App/>, mountNode);
.demo .next-btn {\n margin-right: 5px;\n}
you can easily use validate in Form
, or you can use getError
to set errors where you want to put. See validatorPromise
demo to use promises instead of callbacks.
import { Input, Button, Checkbox, Field } from '@alifd/next';\n\n\n\nconst CheckboxGroup = Checkbox.Group;\n\nconst list = [\n {\n value: 'apple',\n label: 'apple'\n }, {\n value: 'pear',\n label: 'pear'\n }, {\n value: 'orange',\n label: 'orange'\n }\n];\n\nclass App extends React.Component {\n state = {\n checkboxStatus: true\n }\n field = new Field(this, {scrollToFirstError: -10});\n\n isChecked(rule, value, callback) {\n if (!value) {\n return callback('consent agreement not checked ');\n } else {\n return callback();\n }\n }\n\n userName(rule, value, callback) {\n if (value === 'frank') {\n setTimeout(() => callback('name existed'), 200);\n } else {\n setTimeout(() => callback(), 200);\n }\n }\n\n render() {\n const init = this.field.init;\n\n return (<div className=\"demo\">\n <Input {...init('input', {initValue: 'delete all', rules: {required: true}})} />\n {this.field.getError('input') ?\n <span style={{color: 'red'}}>{this.field.getError('input').join(',')}</span> : ''}\n\n <br/>\n <br/>\n\n <Input placeholder=\"try onBlur\" {...init('input1', {\n rules: [{\n required: true,\n message: 'can not be empty',\n trigger: ['onBlur', 'onChange']\n }]\n })} />\n {this.field.getError('input1') ?\n <span style={{color: 'red'}}>{this.field.getError('input1').join(',')}</span> : ''}\n\n <br/>\n <br/>\n\n <Input defaultValue=\"\" placeholder=\"try frank\" {...init('username', {\n rules: [{\n validator: this.userName,\n trigger: ['onBlur', 'onChange']\n }]\n })} />\n {this.field.getState('username') === 'loading' ? 'validating...' : ''}\n {this.field.getError('username') ?\n <span style={{color: 'red'}}>{this.field.getError('username').join(',')}</span> : ''}\n\n <br/>\n <br/>\n\n agreement:\n <Checkbox {...init('checkbox', {\n valueName: 'checked',\n rules: [{validator: this.isChecked}]\n })} />\n {this.field.getError('checkbox') ?\n <span style={{color: 'red'}}>{this.field.getError('checkbox').join(',')}</span> : ''}\n\n <br/>\n <br/>\n\n <Input.TextArea placeholder=\">3 and <10\" {...init('textarea', {\n rules: [{\n required: true,\n minLength: 3,\n maxLength: 10\n }]\n })} />\n {this.field.getError('textarea') ?\n <span style={{color: 'red'}}>{this.field.getError('textarea').join(',')}</span> : ''}\n\n <br/>\n <br/>\n\n {this.state.checkboxStatus ? <div>\n Array validate:\n <CheckboxGroup dataSource={list} {...init('checkboxgroup', {\n rules: [{\n required: true,\n type: 'array',\n message: 'choose one please'\n }]\n })} style={{marginBottom: 10}}/>\n {this.field.getError('checkboxgroup') ?\n <span style={{color: 'red'}}>{this.field.getError('checkboxgroup').join(',')}</span> : ''}\n </div> : null}\n\n <br/>\n <br/>\n\n <Button type=\"primary\" onClick={() => {\n this.field.validate((errors, values) => {\n console.log(errors, values);\n });\n }}>validate</Button>\n <Button onClick={() => {\n this.field.reset();\n }}>reset</Button>\n\n <Button onClick={() => {\n if (this.state.checkboxStatus) {\n this.setState({checkboxStatus: false});\n this.field.remove('checkboxgroup');\n } else {\n this.setState({checkboxStatus: true});\n }\n\n }}>{this.state.checkboxStatus ? 'delete' : 'restore'}</Button>\n </div>);\n }\n}\n\nReactDOM.render(<App/>, mountNode);
.demo .next-btn {\n margin-right: 5px;\n}
校验的错误信息需要用getError
获取
注意
:Form 和 Field 做了深度结合,在 Form 中使用Field,错误信息不需getError
获取会自动展现。
请参考 validatorPromise demo,以使用Promise而不是回调
\n","order":"4"},"codes":{"jsx":"import { Input, Button, Checkbox, Field } from '@alifd/next';\n\n\n\nconst CheckboxGroup = Checkbox.Group;\n\nconst list = [\n {\n value: 'apple',\n label: 'apple'\n }, {\n value: 'pear',\n label: 'pear'\n }, {\n value: 'orange',\n label: 'orange'\n }\n];\n\nclass App extends React.Component {\n state = {\n checkboxStatus: true\n }\n field = new Field(this, {scrollToFirstError: -10});\n\n isChecked(rule, value, callback) {\n if (!value) {\n return callback('consent agreement not checked ');\n } else {\n return callback();\n }\n }\n\n userName(rule, value, callback) {\n if (value === 'frank') {\n setTimeout(() => callback('name existed'), 200);\n } else {\n setTimeout(() => callback(), 200);\n }\n }\n\n render() {\n const init = this.field.init;\n\n return (import { Input, Button, Checkbox, Field } from '@alifd/next';\n\n\n\nconst CheckboxGroup = Checkbox.Group;\n\nconst list = [\n {\n value: 'apple',\n label: 'apple'\n }, {\n value: 'pear',\n label: 'pear'\n }, {\n value: 'orange',\n label: 'orange'\n }\n];\n\nclass App extends React.Component {\n state = {\n checkboxStatus: true\n }\n field = new Field(this, {scrollToFirstError: -10});\n\n isChecked(rule, value, callback) {\n if (!value) {\n return callback('consent agreement not checked ');\n } else {\n return callback();\n }\n }\n\n userName(rule, value, callback) {\n if (value === 'frank') {\n setTimeout(() => callback('name existed'), 200);\n } else {\n setTimeout(() => callback(), 200);\n }\n }\n\n render() {\n const init = this.field.init;\n\n return (<div className=\"demo\">\n <Input {...init('input', {initValue: 'delete all', rules: {required: true}})} />\n {this.field.getError('input') ?\n <span style={{color: 'red'}}>{this.field.getError('input').join(',')}</span> : ''}\n\n <br/>\n <br/>\n\n <Input placeholder=\"try onBlur\" {...init('input1', {\n rules: [{\n required: true,\n message: 'can not be empty',\n trigger: ['onBlur', 'onChange']\n }]\n })} />\n {this.field.getError('input1') ?\n <span style={{color: 'red'}}>{this.field.getError('input1').join(',')}</span> : ''}\n\n <br/>\n <br/>\n\n <Input defaultValue=\"\" placeholder=\"try frank\" {...init('username', {\n rules: [{\n validator: this.userName,\n trigger: ['onBlur', 'onChange']\n }]\n })} />\n {this.field.getState('username') === 'loading' ? 'validating...' : ''}\n {this.field.getError('username') ?\n <span style={{color: 'red'}}>{this.field.getError('username').join(',')}</span> : ''}\n\n <br/>\n <br/>\n\n agreement:\n <Checkbox {...init('checkbox', {\n valueName: 'checked',\n rules: [{validator: this.isChecked}]\n })} />\n {this.field.getError('checkbox') ?\n <span style={{color: 'red'}}>{this.field.getError('checkbox').join(',')}</span> : ''}\n\n <br/>\n <br/>\n\n <Input.TextArea placeholder=\">3 and <10\" {...init('textarea', {\n rules: [{\n required: true,\n minLength: 3,\n maxLength: 10\n }]\n })} />\n {this.field.getError('textarea') ?\n <span style={{color: 'red'}}>{this.field.getError('textarea').join(',')}</span> : ''}\n\n <br/>\n <br/>\n\n {this.state.checkboxStatus ? <div>\n Array validate:\n <CheckboxGroup dataSource={list} {...init('checkboxgroup', {\n rules: [{\n required: true,\n type: 'array',\n message: 'choose one please'\n }]\n })} style={{marginBottom: 10}}/>\n {this.field.getError('checkboxgroup') ?\n <span style={{color: 'red'}}>{this.field.getError('checkboxgroup').join(',')}</span> : ''}\n </div> : null}\n\n <br/>\n <br/>\n\n <Button type=\"primary\" onClick={() => {\n this.field.validate((errors, values) => {\n console.log(errors, values);\n });\n }}>validate</Button>\n <Button onClick={() => {\n this.field.reset();\n }}>reset</Button>\n\n <Button onClick={() => {\n if (this.state.checkboxStatus) {\n this.setState({checkboxStatus: false});\n this.field.remove('checkboxgroup');\n } else {\n this.setState({checkboxStatus: true});\n }\n\n }}>{this.state.checkboxStatus ? 'delete' : 'restore'}</Button>\n </div>);\n }\n}\n\nReactDOM.render(<App/>, mountNode);
.demo .next-btn {\n margin-right: 5px;\n}
validate form values with errors returned wrapped in a promise. Also supports callbacks. If the callback returns a promise, the results of the promise will be returned in a promise from the validate
function.
import ReactDOM from 'react-dom';\nimport React from 'react';\nimport { Input, Button, Checkbox } from '@alifd/next';\nimport Field from '@alifd/field';\n\n\n\nconst CheckboxGroup = Checkbox.Group;\n\nconst list = [\n {\n value: 'apple',\n label: 'apple'\n }, {\n value: 'pear',\n label: 'pear'\n }, {\n value: 'orange',\n label: 'orange'\n }\n];\n\nclass App extends React.Component {\n state = {\n checkboxStatus: true\n }\n field = new Field(this, {scrollToFirstError: -10});\n\n isChecked(rule, value) {\n if (!value) {\n return Promise.reject('consent agreement not checked ');\n } else {\n return Promise.resolve(null);\n }\n }\n\n userName(rule, value) {\n if (value === 'frank') {\n return new Promise((resolve, reject) => {\n setTimeout(() => reject('name existed'), 200);\n });\n } else {\n return new Promise((resolve) => {\n setTimeout(() => resolve(null), 200);\n });\n }\n }\n\n render() {\n const init = this.field.init;\n\n return (<div className=\"demo\">\n <Input {...init('input', {initValue: 'delete all', rules: {required: true}})} />\n {this.field.getError('input') ?\n <span style={{color: 'red'}}>{this.field.getError('input').join(',')}</span> : ''}\n\n <br/>\n <br/>\n\n <Input placeholder=\"try onBlur\" {...init('input1', {\n rules: [{\n required: true,\n message: 'can not be empty',\n trigger: ['onBlur', 'onChange']\n }]\n })} />\n {this.field.getError('input1') ?\n <span style={{color: 'red'}}>{this.field.getError('input1').join(',')}</span> : ''}\n\n <br/>\n <br/>\n\n <Input defaultValue=\"\" placeholder=\"try frank\" {...init('username', {\n rules: [{\n validator: this.userName,\n trigger: ['onBlur', 'onChange']\n }]\n })} />\n {this.field.getState('username') === 'loading' ? 'validating...' : ''}\n {this.field.getError('username') ?\n <span style={{color: 'red'}}>{this.field.getError('username').join(',')}</span> : ''}\n\n <br/>\n <br/>\n\n agreement:\n <Checkbox {...init('checkbox', {\n valueName: 'checked',\n rules: [{validator: this.isChecked}]\n })} />\n {this.field.getError('checkbox') ?\n <span style={{color: 'red'}}>{this.field.getError('checkbox').join(',')}</span> : ''}\n\n <br/>\n <br/>\n\n <Input.TextArea placeholder=\">3 and <10\" {...init('textarea', {\n rules: [{\n required: true,\n minLength: 3,\n maxLength: 10\n }]\n })} />\n {this.field.getError('textarea') ?\n <span style={{color: 'red'}}>{this.field.getError('textarea').join(',')}</span> : ''}\n\n <br/>\n <br/>\n\n {this.state.checkboxStatus ? <div>\n Array validate:\n <CheckboxGroup dataSource={list} {...init('checkboxgroup', {\n rules: [{\n required: true,\n type: 'array',\n message: 'choose one please'\n }]\n })} style={{marginBottom: 10}}/>\n {this.field.getError('checkboxgroup') ?\n <span style={{color: 'red'}}>{this.field.getError('checkboxgroup').join(',')}</span> : ''}\n </div> : null}\n\n <br/>\n <br/>\n\n <Button type=\"primary\" onClick={() => {\n this.field.validatePromise().then(({errors, values}) => {\n console.log(errors, values);\n });\n }}>validate</Button>\n <Button onClick={() => {\n this.field.reset();\n }}>reset</Button>\n\n <Button onClick={() => {\n if (this.state.checkboxStatus) {\n this.setState({checkboxStatus: false});\n this.field.remove('checkboxgroup');\n } else {\n this.setState({checkboxStatus: true});\n }\n\n }}>{this.state.checkboxStatus ? 'delete' : 'restore'}</Button>\n </div>);\n }\n}\n\nReactDOM.render(<App/>, mountNode);
.demo .next-btn {\n margin-right: 5px;\n}
验证表单值,并在承诺中返回错误。也支持回调。如果回调返回承诺,承诺的结果将在 “验证” 函数的承诺中返回。
\n","order":"4"},"codes":{"jsx":"import ReactDOM from 'react-dom';\nimport React from 'react';\nimport { Input, Button, Checkbox } from '@alifd/next';\nimport Field from '@alifd/field';\n\n\n\nconst CheckboxGroup = Checkbox.Group;\n\nconst list = [\n {\n value: 'apple',\n label: 'apple'\n }, {\n value: 'pear',\n label: 'pear'\n }, {\n value: 'orange',\n label: 'orange'\n }\n];\n\nclass App extends React.Component {\n state = {\n checkboxStatus: true\n }\n field = new Field(this, {scrollToFirstError: -10});\n\n isChecked(rule, value) {\n if (!value) {\n return Promise.reject('consent agreement not checked ');\n } else {\n return Promise.resolve(null);\n }\n }\n\n userName(rule, value) {\n if (value === 'frank') {\n return new Promise((resolve, reject) => {\n setTimeout(() => reject('name existed'), 200);\n });\n } else {\n return new Promise((resolve) => {\n setTimeout(() => resolve(null), 200);\n });\n }\n }\n\n render() {\n const init = this.field.init;\n\n return (import ReactDOM from 'react-dom';\nimport React from 'react';\nimport { Input, Button, Checkbox } from '@alifd/next';\nimport Field from '@alifd/field';\n\n\n\nconst CheckboxGroup = Checkbox.Group;\n\nconst list = [\n {\n value: 'apple',\n label: 'apple'\n }, {\n value: 'pear',\n label: 'pear'\n }, {\n value: 'orange',\n label: 'orange'\n }\n];\n\nclass App extends React.Component {\n state = {\n checkboxStatus: true\n }\n field = new Field(this, {scrollToFirstError: -10});\n\n isChecked(rule, value) {\n if (!value) {\n return Promise.reject('consent agreement not checked ');\n } else {\n return Promise.resolve(null);\n }\n }\n\n userName(rule, value) {\n if (value === 'frank') {\n return new Promise((resolve, reject) => {\n setTimeout(() => reject('name existed'), 200);\n });\n } else {\n return new Promise((resolve) => {\n setTimeout(() => resolve(null), 200);\n });\n }\n }\n\n render() {\n const init = this.field.init;\n\n return (<div className=\"demo\">\n <Input {...init('input', {initValue: 'delete all', rules: {required: true}})} />\n {this.field.getError('input') ?\n <span style={{color: 'red'}}>{this.field.getError('input').join(',')}</span> : ''}\n\n <br/>\n <br/>\n\n <Input placeholder=\"try onBlur\" {...init('input1', {\n rules: [{\n required: true,\n message: 'can not be empty',\n trigger: ['onBlur', 'onChange']\n }]\n })} />\n {this.field.getError('input1') ?\n <span style={{color: 'red'}}>{this.field.getError('input1').join(',')}</span> : ''}\n\n <br/>\n <br/>\n\n <Input defaultValue=\"\" placeholder=\"try frank\" {...init('username', {\n rules: [{\n validator: this.userName,\n trigger: ['onBlur', 'onChange']\n }]\n })} />\n {this.field.getState('username') === 'loading' ? 'validating...' : ''}\n {this.field.getError('username') ?\n <span style={{color: 'red'}}>{this.field.getError('username').join(',')}</span> : ''}\n\n <br/>\n <br/>\n\n agreement:\n <Checkbox {...init('checkbox', {\n valueName: 'checked',\n rules: [{validator: this.isChecked}]\n })} />\n {this.field.getError('checkbox') ?\n <span style={{color: 'red'}}>{this.field.getError('checkbox').join(',')}</span> : ''}\n\n <br/>\n <br/>\n\n <Input.TextArea placeholder=\">3 and <10\" {...init('textarea', {\n rules: [{\n required: true,\n minLength: 3,\n maxLength: 10\n }]\n })} />\n {this.field.getError('textarea') ?\n <span style={{color: 'red'}}>{this.field.getError('textarea').join(',')}</span> : ''}\n\n <br/>\n <br/>\n\n {this.state.checkboxStatus ? <div>\n Array validate:\n <CheckboxGroup dataSource={list} {...init('checkboxgroup', {\n rules: [{\n required: true,\n type: 'array',\n message: 'choose one please'\n }]\n })} style={{marginBottom: 10}}/>\n {this.field.getError('checkboxgroup') ?\n <span style={{color: 'red'}}>{this.field.getError('checkboxgroup').join(',')}</span> : ''}\n </div> : null}\n\n <br/>\n <br/>\n\n <Button type=\"primary\" onClick={() => {\n this.field.validatePromise().then(({errors, values}) => {\n console.log(errors, values);\n });\n }}>validate</Button>\n <Button onClick={() => {\n this.field.reset();\n }}>reset</Button>\n\n <Button onClick={() => {\n if (this.state.checkboxStatus) {\n this.setState({checkboxStatus: false});\n this.field.remove('checkboxgroup');\n } else {\n this.setState({checkboxStatus: true});\n }\n\n }}>{this.state.checkboxStatus ? 'delete' : 'restore'}</Button>\n </div>);\n }\n}\n\nReactDOM.render(<App/>, mountNode);
.demo .next-btn {\n margin-right: 5px;\n}
default valueName is value
import { Button, Checkbox, Radio, Switch, Field } from '@alifd/next';\n\n\n\nclass App extends React.Component {\n\n field = new Field(this);\n\n render() {\n const init = this.field.init;\n\n return (<div className=\"demo\">\n <Radio {...init('radio', {initValue: false, valueName: 'checked'})} > checked</Radio>\n <br/>\n <Checkbox {...init('checkbox', {valueName: 'checked', initValue: true})} >\n defaultChecked\n </Checkbox>\n <br/>\n <Switch {...init('switch', {valueName: 'checked', initValue: false})}\n style={{marginTop: 10, marginBottom: 10}}/>\n <br/>\n\n <Button type=\"primary\" onClick={() => {\n console.log(this.field.getValues());\n }}>getValues</Button>\n <Button onClick={() => {\n this.field.setValues({\n radio: true,\n switch: true,\n checkbox: false\n });\n }}> setValues </Button>\n <Button onClick={() => {\n this.field.reset();\n }}>reset</Button>\n </div>);\n }\n}\n\nReactDOM.render(<App/>, mountNode);
.demo .next-btn {\n margin-right: 5px;\n}
valueName 的默认值为 value,如果为其他需要用 valueName 指定
\n","order":"9"},"codes":{"jsx":"import { Button, Checkbox, Radio, Switch, Field } from '@alifd/next';\n\n\n\nclass App extends React.Component {\n\n field = new Field(this);\n\n render() {\n const init = this.field.init;\n\n return (import { Button, Checkbox, Radio, Switch, Field } from '@alifd/next';\n\n\n\nclass App extends React.Component {\n\n field = new Field(this);\n\n render() {\n const init = this.field.init;\n\n return (<div className=\"demo\">\n <Radio {...init('radio', {initValue: false, valueName: 'checked'})} > checked</Radio>\n <br/>\n <Checkbox {...init('checkbox', {valueName: 'checked', initValue: true})} >\n defaultChecked\n </Checkbox>\n <br/>\n <Switch {...init('switch', {valueName: 'checked', initValue: false})}\n style={{marginTop: 10, marginBottom: 10}}/>\n <br/>\n\n <Button type=\"primary\" onClick={() => {\n console.log(this.field.getValues());\n }}>getValues</Button>\n <Button onClick={() => {\n this.field.setValues({\n radio: true,\n switch: true,\n checkbox: false\n });\n }}> setValues </Button>\n <Button onClick={() => {\n this.field.reset();\n }}>reset</Button>\n </div>);\n }\n}\n\nReactDOM.render(<App/>, mountNode);
.demo .next-btn {\n margin-right: 5px;\n}
Fields can be used to manage data when it comes to form data manipulation and validation. After being associated with a component, the form data can be automatically written back, read, and verified.
\ninit
components, value
onChange
must be placed in init's third argument, otherwise it may be overridden by init.Form
has been deeply optimized with Field
for data acquisition
and automatic verification prompt
. It is recommended to use Field
in Form
. Please check Form demo.parseName=true
you could use getValues
to get a struct value, but not work in getValue
you still need pass complete keyClass Demo extends React.Component {\n Field = new Field(this); // instance creation\n\n onClick = ()=>{\n Console.log(this.field.getValue('name'));\n }\n Render() {\n Const init = this.field.init;\n\n // Note: initValue will only be assigned when the component is first initialized. If you are using an asynchronous assignment, use setValue\n Return <div>\n <Input {...init('name',{initValue:'first value'})} />\n <button onClick={this.onClick>Get Data</button>\n </div>\n }\n}
Class Demo extends React.Component {\n Field = new Field(this);\n\n onClick = ()=>{\n this.field.setValue('name', 'newvalue'); // Assignment will automatically trigger render\n }\n Render() {\n Const init = this.field.init;\n\n Return <div>\n <Input {...init('name')} />\n <button onClick={this.onClick}>Settings</button>\n </div>\n }\n}
Class Demo extends React.Component {\n Field = new Field(this);\n\n // Set the data before the component is mounted (this can be replaced with initValue)\n componentWillMount() {\n this.field.setValue('name', 'init Name')\n }\n // Receive data from props\n componentWillReceiveProps(nextProps) {\n this.field.setValue('name', nextProps.name)\n }\n Render() {\n Const init = this.field.init;\n\n Return <div>\n <Input {...init('name')} />\n </div>\n }\n}
Class Demo extends React.Component {\n Field = new Field(this);\n\n onClick = ()=>{\n Ajax({\n Url:'/demo.json',\n Success:(json)=>{\n // Update of assignment in callback event\n this.field.setValue('name',json.name);\n }\n });\n }\n Render() {\n Const init = this.field.init;\n\n Return <div>\n <Input {...init('name')} />\n <button onClick={this.onClick}>Settings</button>\n </div>\n }\n}
Two usages:
\nClass Demo extends React.Component {\n Field = new Field(this,{\n onChange:(name, value) => {\n Switch(name) {\n Case 'name1':\n this.field.setValue('name2','value set by name1');\n Break;\n Case 'name2':\n this.field.setValue('name1','value set by name2');\n Break;\n }\n }\n });\n Render() {\n Const init = this.field.init;\n\n Return <div>\n <Input {...init('name1')} />\n <Input {...init('name2')} />\n </div>\n }\n}
Class Demo extends React.Component {\n Render() {\n Const init = this.field.init;\n\n Return <div>\n <Input {...init('name1',{\n Props:{\n onChange:(v)=>{\n this.field.setValue('name2','value set by name1');\n }\n }\n })} />\n <Input {...init('name2',{\n Props:{\n onChange:(v)=>{\n this.field.setValue('name1','value set by name2');\n }\n }\n })} />\n </div>\n }\n}
For details, please check Demo Demo Associate Control
Let myfield = new Field(this [,options]);\n\nor with hooks\n\nlet myfield = Field.useField([options]); // react version must > 16.8
Parameter | \nDescription | \nType | \nOptional | \nDefault | \n
---|---|---|---|---|
this | \nThe incoming call to this class | \nReact.Component | \nmust be set | \n|
options | \nSome event configuration, detailed parameters are as follows | \nObject | \nNot required | \n
options
configuration item
Parameters | \nDescription | \nType | \nDefault | \n
---|---|---|---|
onChange | \nall component changes will arrive here [setValue won't trigger the function] | \nFunction(name,value) | \n\n |
parseName | \nWhether to translate name in init(name) (getValues will convert a string with . to an object) | \nBoolean | \nfalse | \n
forceUpdate | \nOnly the components of PureComponent are recommended to open this forced refresh function, which will cause performance problems (500 components as an example: the render will cost 700ms when it is turned on, and 400ms if it is turned off) | \nBoolean | \nfalse | \n
scrollToFirstError | \nscrolling field.validate scrolls to the first errored component, offsets if it is an integer | \nBoolean/Number | \ntrue | \n
autoUnmount | \nAutomatically delete the Unmout element, if you want to keep the data can be set to false | \nBoolean | \ntrue | \n
autoValidate | \nAutomatically validate while value changed | \nBoolean | \ntrue | \n
values | \ninitial value | \nObject | \n
The api interface provided by the object after new
(eg myfield.getValues()
) (The api function starting with set
should not be manipulated in render, which may trigger an infinite loop)
Parameter | \nDescription | \nType | \nOptional | \nDefault | \n
---|---|---|---|---|
init | \nInitialize each component, [Detailed Parameters below] (#init)) | \nFunction(name:String, option:Object) | \n\n | \n |
getValues | \nGet the value of a group of input controls. If no parameters are passed, get the values of all components | \nFunction([names: String[]]) | \n||
getValue | \nget the value of a single input control | \nFunction(name: String) | \n||
setValues | \nSets the value of a set of input controls (triggers render, follow the use of react time) | \nFunction(obj: Object) | \n||
setValue | \nSets the value of a single input control (triggers render, follow the use of react time) | \nFunction(name: String, value) | \n||
Validate | \nValidate and retrieve the values of a set of input fields and Error | \nFunction([names: String[]], callback: Function(errors, values)) | \n\n | \n |
getError | \nGet Error of a Single Input Control | \nFunction(name: String) | \n\n | \n |
getErrors | \nGet Errors of a Group of Input Controls | \nFunction([name: String]) | \n\n | \n |
setError | \nSet Error for a Single Input Control | \nFunction(name: String, errors:String/Array[String]) | \n\n | \n |
setErrors | \nSet Errors of a Group of Input Controls | \nFunction(obj: Object) | \n\n | \n |
reset | \nreset the value of a group of input controls, clear the checksum | \nFunction([names: String[]]) | \n\n | \n |
resetToDefault | \nResets the value of a group of input controls to the default | \nFunction([names: String[]]) | \n\n | \n |
getState | \nJudge check status | \nFunction(name: String) | \n'error' 'success' 'loading' '' | \n'' | \n
getNames | \nGet the key of all components | \nFunction() | \n\n | \n |
remove | \nDelete the data of a certain control or a group of controls. After deletion, the validate/value associated with it will be cleared. | \nFunction(name: String/String[]) | \n||
spliceArray | \ndelete data of name like name.{index} | \nFunction(keyMatch: String, index: Number) | \n\n |
init(name, options, props)
Parameter | \nDescription | \nType | \nOptional | \nDefault | \n|
---|---|---|---|---|---|
name | \nRequired unique input control symbol | \nString | \n|||
options.valueName | \nattribute name of the component value, such as Checkbox is checked , Input is value | \nString | \n\n | 'value' | \n|
options.initValue | \nThe initial value of the component (the component will be read only when rendering for the first time, and later modifying this value is invalid), similar to defaultValue | \nany | \n\n | \n | |
options.trigger | \nName of the event that triggered the data change | \nString | \n\n | 'onChange' | \n|
options.rules | \nChecksum Rules | \nArray/Object | \n\n | \n | \n |
options.getValueFromEvent | \ncustom way to get value from onChange event, generally do not need to set. Detailed usage see demo custom data get | \nFunction(value, ...args) parameter order and components are exactly the same The | \n\n | \n | \n |
props | \nComponent-defined events can be written here | \nObject | \n\n | \n | \n |
autoValidate | \nAutomatically validate while value changed | \nBoolean | \ntrue | \n
return
\n{id,value,onChange}
{\n rules:[{ required: true }]\n}
multiple rule
\n{\n rules:[{required:true,trigger:'onBlur'},{pattern:/abcd/,message:'match abcd'},{validator:(rule, value, callback)=>{callback('got error')}}]\n}
Parameter | \nDescription | \nType | \nOptional | \n||
---|---|---|---|---|---|
required | \ncannot be empty | \nBoolean | \ntrue | \nundefined/null/"/[] will trigger this rule) | \n|
pattern | \ncheck regular expression | \nregular | \n\n | \n | |
minLength | \nMinimum string length / Minimum number of arrays | \nNumber | \n\n | String/Number/Array | \n|
maxLength | \nMaximum length of string / Maximum number of arrays | \nNumber | \n\n | String/Number/Array | \n|
length | \nstring exact length / exact number of arrays | \n\n | number | \n\n | String/Number/Array | \n
min | \nMin | \nNumber | \n\n | String/Number | \n|
max | \nmaximum | \nNumber | \n\n | String/Number | \n|
format | \nsum of common patterns | \nString | \nurl, email, tel, number | \nString | \n|
validator | \nCustom validation, (don't forget to execute callback() when validation is successful, otherwise validation will not return) | \nFunction(rule,value,callback) | \n|||
trigger | \nName of the event that triggered the check | \nString/Array | \nonChange/onBlur/... | \nonChange | \n|
message | \nerror message | \nString | \n\n |
Supports controlled mode (value+onChange) Must
One complete operation throws an onChange event\n For example, there is a process that indicates the status of the progress, it is recommended to increase the API onProcess
; if there is a Start indicates the startup state, it is recommended to increase the API onStart
Clear data when value={undefined}
, field's reset function will send undefined data to all components
componentWillReceiveProps(nextProps) {\n if ('value' in nextProps ) {\n this.setState({\n value: nextProps.value === undefined? []: nextProps.value // set value after clear\n })\n }\n}
this.field.validate
manually? A: Is it safe to define the validator method to ensure that the callback
can be executed on any branch?涉及到表单数据操作、校验的地方都可以用Field来管理数据。和组件关联后可以自动对表单数据进行回写、读取、校验。
\ninit
过的组件, value
onChange
必须放在 init 的第三个参数, 否则有可能被 init 覆盖。Form
已经和Field
在数据获取
和自动校验提示
方面做了深度优化,建议在Form
中使用Field
, 请查看 Form demo。自动卸载的组件
数据请关闭此项parseName=true
可以通过 getValues
获取到结构化的数据, 但是 getValue 还是必须传完整 key 值class Demo extends React.Component {\n field = new Field(this); // 实例创建\n\n onClick = ()=>{\n console.log(this.field.getValue('name'));\n }\n render() {\n const init = this.field.init;\n\n // 注意:initValue只会在组件第一次初始化的时候被赋值,如果你是异步赋值请用setValue\n return <div>\n <Input {...init('name',{initValue:'first value'})} />\n <button onClick={this.onClick}>获取数据</button>\n </div>\n }\n}
class Demo extends React.Component {\n field = new Field(this);\n\n onClick = ()=>{\n this.field.setValue('name', 'newvalue'); // 赋值会自动触发render\n }\n render() {\n const init = this.field.init;\n\n return <div>\n <Input {...init('name')} />\n <button onClick={this.onClick}>设置数据</button>\n </div>\n }\n}
class Demo extends React.Component {\n field = new Field(this);\n\n // 在组件挂载之前把数据设置进去(可以用initValue替代这种用法)\n componentWillMount() {\n this.field.setValue('name', 'init Name')\n }\n // 接收来自props的数据\n componentWillReceiveProps(nextProps) {\n this.field.setValue('name', nextProps.name)\n }\n render() {\n const init = this.field.init;\n\n return <div>\n <Input {...init('name')} />\n </div>\n }\n}
class Demo extends React.Component {\n field = new Field(this);\n\n onClick = ()=>{\n Ajax({\n url:'/demo.json',\n success:(json)=>{\n // 回调事件中赋值更新\n this.field.setValue('name',json.name);\n }\n });\n }\n render() {\n const init = this.field.init;\n\n return <div>\n <Input {...init('name')} />\n <button onClick={this.onClick}>设置数据</button>\n </div>\n }\n}
两种用法:
\nclass Demo extends React.Component {\n field = new Field(this,{\n onChange:(name, value) => {\n switch(name) {\n case 'name1':\n this.field.setValue('name2','value set by name1');\n break;\n case 'name2':\n this.field.setValue('name1','value set by name2');\n break;\n }\n }\n });\n render() {\n const init = this.field.init;\n\n return <div>\n <Input {...init('name1')} />\n <Input {...init('name2')} />\n </div>\n }\n}
class Demo extends React.Component {\n render() {\n const init = this.field.init;\n\n return <div>\n <Input {...init('name1',{\n props:{\n onChange:(v)=>{\n this.field.setValue('name2','value set by name1');\n }\n }\n })} />\n <Input {...init('name2',{\n props:{\n onChange:(v)=>{\n this.field.setValue('name1','value set by name2');\n }\n }\n })} />\n </div>\n }\n}
详细请查看demo演示 关联控制
let myfield = new Field(this [,options]);\n\n或者使用hooks\n\nlet myfield = Field.useField([options]); // 要求 react 版本 > 16.8
参数 | \n说明 | \n类型 | \n可选值 | \n默认值 | \n
---|---|---|---|---|
this | \n传入调用class的this | \nReact.Component | \n必须设置 | \n\n |
options | \n一些事件配置, 详细参数如下 | \nObject | \n非必须 | \n
options
配置项
参数 | \n说明 | \n类型 | \n默认值 | \n
---|---|---|---|
onChange | \n所有组件的change都会到达这里[setValue不会触发该函数] | \nFunction(name,value) | \n\n |
parseName | \n是否翻译init(name) 中的name (getValues会把带. 的字符串转换成对象) | \nBoolean | \nfalse | \n
forceUpdate | \n仅建议PureComponent的组件打开此强制刷新功能,会带来性能问题(500个组件为例:打开的时候render花费700ms, 关闭时候render花费400ms) | \nBoolean | \nfalse | \n
scrollToFirstError | \nfield.validate的时候滚动到第一个出错的组件, 如果是整数会进行偏移 | \nBoolean/Number | \ntrue | \n
autoUnmount | \n自动删除Unmout元素,如果想保留数据可以设置为false | \nBoolean | \ntrue | \n
autoValidate | \n是否修改数据的时候就自动触发校验, 设为 false 后只能通过 validate() 来触发校验 | \nBoolean | \ntrue | \n
values | \n初始化数据 | \nObject | \n
new
之后的对象提供的api接口 (例:myfield.getValues()
)(set
开头的api函数不要在render里面操作, 可能会触发死循环)
参数 | \n说明 | \n类型 | \n可选值 | \n默认值 | \n
---|---|---|---|---|
init | \n初始化每个组件,详细参数如下) | \nFunction(name:String, option:Object) | \n\n | \n |
getValues | \n获取一组输入控件的值,如不传入参数,则获取全部组件的值 | \nFunction([names: String[]]) | \n\n | \n |
getValue | \n获取单个输入控件的值 | \nFunction(name: String) | \n\n | \n |
setValues | \n设置一组输入控件的值(会触发render,请遵循react时机使用) | \nFunction(obj: Object) | \n\n | \n |
setValue | \n设置单个输入控件的值 (会触发render,请遵循react时机使用) | \nFunction(name: String, value) | \n\n | \n |
validate | \n校验并获取一组输入域的值与 Error | \nFunction([names: String[]], callback: Function(errors, values)) | \n\n | \n |
getError | \n获取单个输入控件的 Error | \nFunction(name: String) | \n\n | \n |
getErrors | \n获取一组输入控件的 Error | \nFunction([name: String]) | \n\n | \n |
setError | \n设置单个输入控件的 Error | \nFunction(name: String, errors:String/Array[String]) | \n\n | \n |
setErrors | \n设置一组输入控件的 Error | \nFunction(obj: Object) | \n\n | \n |
reset | \n重置一组输入控件的值、清空校验 | \nFunction([names: String[]]) | \n\n | \n |
resetToDefault | \n重置一组输入控件的值为默认值 | \nFunction([names: String[]]) | \n\n | \n |
getState | \n判断校验状态 | \nFunction(name: String) | \n'error' 'success' 'loading' '' | \n'' | \n
getNames | \n获取所有组件的key | \nFunction() | \n\n | \n |
remove | \n删除某一个或者一组控件的数据,删除后与之相关的validate/value都会被清空 | \nFunction(name: String/String[]) | \n\n | \n |
spliceArray | \n删除 name 是数组格式的数据, 并且自动处理其他 name 的数组错位问题 | \nFunction(keyMatch: String, index: Number) | \n\n |
init(name, options, props)
参数 | \n说明 | \n类型 | \n可选值 | \n默认值 | \n|
---|---|---|---|---|---|
name | \n必填输入控件唯一标志 | \nString | \n\n | \n | |
options.valueName | \n组件值的属性名称,如 Checkbox 的是 checked ,Input是 value | \nString | \n\n | 'value' | \n|
options.initValue | \n组件初始值(组件第一次render的时候才会读取,后面再修改此值无效),类似defaultValue | \nany | \n\n | \n | |
options.trigger | \n触发数据变化的事件名称 | \nString | \n\n | 'onChange' | \n|
options.rules | \n校验规则 | \nArray/Object | \n\n | \n | \n |
options.getValueFromEvent | \n自定义从onChange 事件中获取value的方式,一般不需要设置. 详细用法查看demo 自定义数据获取 | \nFunction(value,...args) 参数顺序和组件是完全一致的 | \n\n | \n | \n |
props | \n组件自定义的事件可以写在这里 | \nObject | \n\n | \n | \n |
autoValidate | \n是否修改数据的时候自动触发校验单个组件的校验, 设为 false 后只能通过 validate() 来触发校验 | \nBoolean | \ntrue | \n
返回值
\n{id,value,onChange}
{\n rules:[{ required: true }]\n}
多个rule
\n{\n rules:[{required:true,trigger:'onBlur'},{pattern:/abcd/,message:'abcd不能缺'},{validator:(rule, value, callback)=>{callback('出错了')}}]\n}
参数 | \n说明 | \n类型 | \n可选值 | \n使用类型 | \n
---|---|---|---|---|
required | \n不能为空 | \nBoolean | \ntrue | \nundefined/null/“”/[] 会触发此规则) | \n
pattern | \n校验正则表达式 | \n正则 | \n\n | \n |
minLength | \n字符串最小长度 / 数组最小个数 | \nNumber | \n\n | String/Number/Array | \n
maxLength | \n字符串最大长度 / 数组最大个数 | \nNumber | \n\n | String/Number/Array | \n
length | \n字符串精确长度 / 数组精确个数 | \nNumber | \n\n | String/Number/Array | \n
min | \n最小值 | \nNumber | \n\n | String/Number | \n
max | \n最大值 | \nNumber | \n\n | String/Number | \n
format | \n对常用 pattern 的总结 | \nString | \nurl、email、tel、number | \nString | \n
validator | \n自定义校验,(校验成功的时候不要忘记执行 callback() ,否则会校验不返回) | \nFunction(rule,value,callback) | \n\n | \n |
trigger | \n触发校验的事件名称 | \nString/Array | \nonChange/onBlur/... | \nonChange | \n
message | \n出错时候信息 | \nString | \n\n |
支持受控模式(value+onChange) 必须
一次完整操作抛一次onChange事件 建议
\n比如有Process表示进展中的状态,建议增加API onProcess
;如果有Start表示启动状态,建议增加API onStart
value={undefined}
的时候清空数据, field 的 reset 函数会给所有组件下发 undefined 数据 建议
componentWillReceiveProps(nextProps) {\n if ('value' in nextProps ) {\n this.setState({\n value: nextProps.value === undefined? []: nextProps.value // 设置组件的被清空后的数值\n })\n }\n}
this.field.validate
的时候进不了回调函数? 答: 是不是自定义了validator方法,确保callback
在任何分支下都能被执行到。For required fields, set the aria-required
attribute in the component and prompt the user with a visual design highlight.
import { Form, Input, Select, Radio, Checkbox, DatePicker, Switch, Upload, Grid, Field } from '@alifd/next';\n\nconst RadioGroup = Radio.Group;\nconst {Row, Col} = Grid;\nconst FormItem = Form.Item;\nconst Option = Select.Option;\nconst formItemLayout = {\n labelCol: {\n span: 7\n },\n wrapperCol: {\n span: 16\n }\n};\nclass Demo extends React.Component {\n state = {\n size: 'medium'\n };\n submitHandle = (e) => {\n console.log(e);\n };\n render() {\n return (\n <div>\n <Form {...formItemLayout} size={this.state.size} style={{maxWidth: '800px'}}>\n <FormItem required label=\"username:\">\n <Input placeholder=\"Please enter your username\" id=\"a11yUsername\" name=\"a11yUsername\" aria-required=\"true\" />\n </FormItem>\n <FormItem required label=\"Password:\">\n <Input htmlType=\"password\" placeholder=\"Please enter your password\" id=\"a11yPassword\" name=\"a11yPassword\" aria-required=\"true\" />\n </FormItem>\n <FormItem \n id=\"myDateInput-1\"\n required\n label=\"Accessible Date 1 (YYYY/MM/DD):\"\n requiredMessage=\"Please select your date\"\n >\n <DatePicker name=\"a11yDate\" format=\"YYYY/MM/DD\" inputProps={{\"aria-required\": \"true\", \"id\": \"myDateInput-1\"}}/> \n </FormItem>\n <FormItem \n required\n label=\"Accessible Date 2 (YYYY/MM/DD):\"\n requiredMessage=\"Please select your date\"\n >\n <DatePicker name=\"a11yOtherDate\" format=\"YYYY/MM/DD\" dateInputAriaLabel=\"Date input format YYYY/MM/DD\" inputProps={{\"aria-required\": \"true\", \"aria-label\": \"Accessible Date 2\"}}/> \n </FormItem>\n <FormItem label=\"Switch:\">\n <Switch name=\"a11ySwitch\" aria-label=\"Accessible Switch\" defaultChecked/>\n </FormItem>\n <FormItem\n required\n label=\"gender:\"\n requiredMessage=\"Please select your gender\"\n >\n <RadioGroup name=\"a11ySex\">\n <Radio value=\"male\" aria-required=\"true\">Male</Radio>\n <Radio value=\"female\" aria-required=\"true\">Female</Radio>\n </RadioGroup>\n </FormItem>\n <FormItem label=\"Language:\">\n <Checkbox.Group name=\"a11yLangs\" aria-label=\"Please select a programming language\">\n <Checkbox value=\"python\">python</Checkbox>\n <Checkbox value=\"java\">java</Checkbox>\n <Checkbox value=\"angular\">angular</Checkbox>\n <Checkbox value=\"c\">c</Checkbox>\n <Checkbox value=\"other\">other</Checkbox>\n </Checkbox.Group>\n </FormItem>\n <FormItem label=\"upload:\">\n <Upload.Card\n listType=\"card\"\n action=\"https://www.easy-mock.com/mock/5b713974309d0d7d107a74a3/alifd/upload\"\n accept=\"image/png, image/jpg, image/jpeg, image/gif, image/bmp\"\n defaultValue={[]}\n limit={2}\n name=\"a11yUpload\"\n />\n </FormItem>\n <FormItem label=\"Note:\">\n <Input.TextArea placeholder=\"description\" name=\"a11yRemark\"/>\n </FormItem>\n <FormItem wrapperCol={{offset: 5}}>\n <Form.Submit validate type=\"primary\" onClick={this.submitHandle} style={{marginRight: 7}}>Submit</Form.Submit>\n <Form.Reset style={{marginLeft: 130}}>Reset</Form.Reset>\n </FormItem>\n </Form>\n </div>\n );\n }\n}\nReactDOM.render(<Demo />, mountNode);
对于必填项,在组件中要设置aria-required
属性,并通过视觉设计上的高亮提示用户。
import { Form, Input, Select, Radio, Checkbox, DatePicker, Switch, Upload, Grid, Field } from '@alifd/next';\n\nconst RadioGroup = Radio.Group;\nconst {Row, Col} = Grid;\nconst FormItem = Form.Item;\nconst Option = Select.Option;\nconst formItemLayout = {\n labelCol: {\n span: 7\n },\n wrapperCol: {\n span: 16\n }\n};\nclass Demo extends React.Component {\n state = {\n size: 'medium'\n };\n submitHandle = (e) => {\n console.log(e);\n };\n render() {\n return (\n <div>\n <Form {...formItemLayout} size={this.state.size} style={{maxWidth: '800px'}}>\n <FormItem required label=\"username:\">\n <Input placeholder=\"Please enter your username\" id=\"a11yUsername\" name=\"a11yUsername\" aria-required=\"true\" />\n </FormItem>\n <FormItem required label=\"Password:\">\n <Input htmlType=\"password\" placeholder=\"Please enter your password\" id=\"a11yPassword\" name=\"a11yPassword\" aria-required=\"true\" />\n </FormItem>\n <FormItem \n id=\"myDateInput-1\"\n required\n label=\"Accessible Date 1 (YYYY/MM/DD):\"\n requiredMessage=\"Please select your date\"\n >\n <DatePicker name=\"a11yDate\" format=\"YYYY/MM/DD\" inputProps={{\"aria-required\": \"true\", \"id\": \"myDateInput-1\"}}/> \n </FormItem>\n <FormItem \n required\n label=\"Accessible Date 2 (YYYY/MM/DD):\"\n requiredMessage=\"Please select your date\"\n >\n <DatePicker name=\"a11yOtherDate\" format=\"YYYY/MM/DD\" dateInputAriaLabel=\"Date input format YYYY/MM/DD\" inputProps={{\"aria-required\": \"true\", \"aria-label\": \"Accessible Date 2\"}}/> \n </FormItem>\n <FormItem label=\"Switch:\">\n <Switch name=\"a11ySwitch\" aria-label=\"Accessible Switch\" defaultChecked/>\n </FormItem>\n <FormItem\n required\n label=\"gender:\"\n requiredMessage=\"Please select your gender\"\n >\n <RadioGroup name=\"a11ySex\">\n <Radio value=\"male\" aria-required=\"true\">Male</Radio>\n <Radio value=\"female\" aria-required=\"true\">Female</Radio>\n </RadioGroup>\n </FormItem>\n <FormItem label=\"Language:\">\n <Checkbox.Group name=\"a11yLangs\" aria-label=\"Please select a programming language\">\n <Checkbox value=\"python\">python</Checkbox>\n <Checkbox value=\"java\">java</Checkbox>\n <Checkbox value=\"angular\">angular</Checkbox>\n <Checkbox value=\"c\">c</Checkbox>\n <Checkbox value=\"other\">other</Checkbox>\n </Checkbox.Group>\n </FormItem>\n <FormItem label=\"upload:\">\n <Upload.Card\n listType=\"card\"\n action=\"https://www.easy-mock.com/mock/5b713974309d0d7d107a74a3/alifd/upload\"\n accept=\"image/png, image/jpg, image/jpeg, image/gif, image/bmp\"\n defaultValue={[]}\n limit={2}\n name=\"a11yUpload\"\n />\n </FormItem>\n <FormItem label=\"Note:\">\n <Input.TextArea placeholder=\"description\" name=\"a11yRemark\"/>\n </FormItem>\n <FormItem wrapperCol={{offset: 5}}>\n <Form.Submit validate type=\"primary\" onClick={this.submitHandle} style={{marginRight: 7}}>Submit</Form.Submit>\n <Form.Reset style={{marginLeft: 130}}>Reset</Form.Reset>\n </FormItem>\n </Form>\n </div>\n );\n }\n}\nReactDOM.render(<Demo />, mountNode);
The width of the label does not change when the browser is stretched.
\nIf the component is relatively high, you can use className="next-form-text-align"
to adjust.
import { Form, Input, Checkbox } from '@alifd/next';\n\n\nconst FormItem = Form.Item;\n\nconst formItemLayout = {\n labelCol: {\n fixedSpan: 10\n },\n wrapperCol: {\n span: 14\n }\n};\n\nclass Demo extends React.Component {\n\n handleSubmit = (values) => {\n console.log('Get form value:', values);\n };\n\n render() {\n return (\n <Form style={{width: '60%'}} {...formItemLayout} >\n <FormItem label=\"baseUsername:\">\n <p>Fixed Name</p>\n </FormItem>\n <FormItem label=\"password:\">\n <Input htmlType=\"password\" name=\"basePass\" placeholder=\"Please Enter Password\"/>\n </FormItem>\n <FormItem label=\"Note:\" help=\"something\">\n <Input.TextArea placeholder=\"something\" name=\"baseRemark\" />\n </FormItem>\n <FormItem label=\"Agreement:\">\n <Checkbox name=\"baseAgreement\" defaultChecked>Agree</Checkbox>\n </FormItem>\n <FormItem label=\" \">\n <Form.Submit onClick={this.handleSubmit}>Confirm</Form.Submit>\n </FormItem>\n </Form>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
拉伸浏览器的时候label宽度不变。
\n如果组件比较靠上,可以用 className="next-form-text-align"
做调整
import { Form, Input, Checkbox } from '@alifd/next';\n\n\nconst FormItem = Form.Item;\n\nconst formItemLayout = {\n labelCol: {\n fixedSpan: 10\n },\n wrapperCol: {\n span: 14\n }\n};\n\nclass Demo extends React.Component {\n\n handleSubmit = (values) => {\n console.log('Get form value:', values);\n };\n\n render() {\n return (\n <Form style={{width: '60%'}} {...formItemLayout} >\n <FormItem label=\"baseUsername:\">\n <p>Fixed Name</p>\n </FormItem>\n <FormItem label=\"password:\">\n <Input htmlType=\"password\" name=\"basePass\" placeholder=\"Please Enter Password\"/>\n </FormItem>\n <FormItem label=\"Note:\" help=\"something\">\n <Input.TextArea placeholder=\"something\" name=\"baseRemark\" />\n </FormItem>\n <FormItem label=\"Agreement:\">\n <Checkbox name=\"baseAgreement\" defaultChecked>Agree</Checkbox>\n </FormItem>\n <FormItem label=\" \">\n <Form.Submit onClick={this.handleSubmit}>Confirm</Form.Submit>\n </FormItem>\n </Form>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
Label Position: top / left
\nWith Row
Col
control the layout of the elements within the form (Note: FormItem is not Form direct child elements can not directly set the layout on the Form)
import { Form, Input, Switch, Grid, Button, Icon, Balloon } from '@alifd/next';\n\n\nconst FormItem = Form.Item;\nconst {Row, Col} = Grid;\n\nconst style = {\n padding: '20px',\n background: '#F7F8FA',\n margin: '20px'\n};\nconst formItemLayout = {\n labelCol: {fixedSpan: 4}\n};\nconst label = (<span>\nname:<Balloon type=\"primary\" trigger={<Icon type=\"prompt\" size=\"small\" />} closable={false}>blablablablablablablabla</Balloon>\n</span>);\n\nclass Demo extends React.Component {\n state = {\n labelAlign: 'top'\n }\n handleChange = (v) => {\n this.setState({\n labelAlign: v ? 'left' : 'top'\n });\n }\n render() {\n const labelAlign = this.state.labelAlign;\n\n return (\n <div>\n <h3>Label Position</h3>\n <Switch checkedChildren=\"left\" unCheckedChildren=\"top\" checked={this.state.labelAlign === 'left'} onChange={this.handleChange} />\n\n <Form style={style}>\n <Row gutter=\"4\">\n <Col>\n <FormItem {...formItemLayout} labelAlign={labelAlign}\n label={label}\n required\n >\n <Input placeholder=\"Enter a search name:\"/>\n </FormItem>\n <FormItem {...formItemLayout} labelAlign={labelAlign}\n label=\"Long search name:\"\n >\n <Input placeholder=\"Enter a search name:\"/>\n </FormItem>\n <FormItem {...formItemLayout} labelAlign={labelAlign}\n label=\"Search name:\"\n >\n <Input placeholder=\"Enter a search name:\"/>\n </FormItem>\n </Col>\n <Col>\n <FormItem {...formItemLayout} labelAlign={labelAlign}\n label=\"Search name:\"\n >\n <Input placeholder=\"Enter a search name:\"/>\n </FormItem>\n <FormItem {...formItemLayout} labelAlign={labelAlign}\n label=\"Long search name:\"\n >\n <Input placeholder=\"Enter a search name:\"/>\n </FormItem>\n <FormItem {...formItemLayout} labelAlign={labelAlign}\n label=\"Search name:\"\n >\n <Input placeholder=\"Enter a search name:\"/>\n </FormItem>\n </Col>\n <Col>\n <FormItem {...formItemLayout} labelAlign={labelAlign}\n label=\"Search name:\"\n >\n <Input placeholder=\"Enter a search name:\"/>\n </FormItem>\n <FormItem {...formItemLayout} labelAlign={labelAlign}\n label=\"Long search name:\"\n >\n <Input placeholder=\"Enter a search name:\"/>\n </FormItem>\n <FormItem {...formItemLayout} labelAlign={labelAlign}\n label=\"Search name:\"\n >\n <Input placeholder=\"Enter a search name:\"/>\n </FormItem>\n </Col>\n </Row>\n <Row>\n <Col style={{ textAlign: 'right' }}>\n <Button type=\"primary\" style={{ marginRight: '5px' }}>Search</Button>\n <Button >Clear All</Button>\n </Col>\n </Row>\n </Form>\n\n\n <Form style={style}>\n <Row gutter=\"4\">\n <Col>\n <FormItem {...formItemLayout} labelAlign={labelAlign}\n label={label}\n required\n >\n <Input placeholder=\"Enter a search name:\"/>\n </FormItem>\n </Col>\n <Col>\n <FormItem {...formItemLayout} labelAlign={labelAlign}\n label=\"Long search name:\"\n >\n <Input placeholder=\"Enter a search name:\"/>\n </FormItem>\n </Col>\n <Col>\n <FormItem {...formItemLayout} labelAlign={labelAlign}\n label=\"Search name:\"\n >\n <Input placeholder=\"Enter a search name:\"/>\n </FormItem>\n </Col>\n <Col>\n <FormItem {...formItemLayout} labelAlign={labelAlign}\n label=\"Search name:\"\n >\n <Input placeholder=\"Enter a search name:\"/>\n </FormItem>\n </Col>\n <Col>\n <FormItem {...formItemLayout} labelAlign={labelAlign}\n label=\"Search name:\"\n >\n <Input placeholder=\"Enter a search name:\"/>\n </FormItem>\n </Col>\n </Row>\n <Row>\n <Col style={{ textAlign: 'right' }}>\n <Button type=\"primary\" style={{ marginRight: '5px' }}>Search</Button>\n <Button >Clear All</Button>\n </Col>\n </Row>\n </Form>\n </div>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
标签位置:上、左
\n配合 Row
Col
控制表单内元素布局 (注意:FormItem非Form直接子元素需要不能直接直接在Form上设置布局)
import { Form, Input, Switch, Grid, Button, Icon, Balloon } from '@alifd/next';\n\n\nconst FormItem = Form.Item;\nconst {Row, Col} = Grid;\n\nconst style = {\n padding: '20px',\n background: '#F7F8FA',\n margin: '20px'\n};\nconst formItemLayout = {\n labelCol: {fixedSpan: 4}\n};\nconst label = (<span>\nname:<Balloon type=\"primary\" trigger={<Icon type=\"prompt\" size=\"small\" />} closable={false}>blablablablablablablabla</Balloon>\n</span>);\n\nclass Demo extends React.Component {\n state = {\n labelAlign: 'top'\n }\n handleChange = (v) => {\n this.setState({\n labelAlign: v ? 'left' : 'top'\n });\n }\n render() {\n const labelAlign = this.state.labelAlign;\n\n return (\n <div>\n <h3>Label Position</h3>\n <Switch checkedChildren=\"left\" unCheckedChildren=\"top\" checked={this.state.labelAlign === 'left'} onChange={this.handleChange} />\n\n <Form style={style}>\n <Row gutter=\"4\">\n <Col>\n <FormItem {...formItemLayout} labelAlign={labelAlign}\n label={label}\n required\n >\n <Input placeholder=\"Enter a search name:\"/>\n </FormItem>\n <FormItem {...formItemLayout} labelAlign={labelAlign}\n label=\"Long search name:\"\n >\n <Input placeholder=\"Enter a search name:\"/>\n </FormItem>\n <FormItem {...formItemLayout} labelAlign={labelAlign}\n label=\"Search name:\"\n >\n <Input placeholder=\"Enter a search name:\"/>\n </FormItem>\n </Col>\n <Col>\n <FormItem {...formItemLayout} labelAlign={labelAlign}\n label=\"Search name:\"\n >\n <Input placeholder=\"Enter a search name:\"/>\n </FormItem>\n <FormItem {...formItemLayout} labelAlign={labelAlign}\n label=\"Long search name:\"\n >\n <Input placeholder=\"Enter a search name:\"/>\n </FormItem>\n <FormItem {...formItemLayout} labelAlign={labelAlign}\n label=\"Search name:\"\n >\n <Input placeholder=\"Enter a search name:\"/>\n </FormItem>\n </Col>\n <Col>\n <FormItem {...formItemLayout} labelAlign={labelAlign}\n label=\"Search name:\"\n >\n <Input placeholder=\"Enter a search name:\"/>\n </FormItem>\n <FormItem {...formItemLayout} labelAlign={labelAlign}\n label=\"Long search name:\"\n >\n <Input placeholder=\"Enter a search name:\"/>\n </FormItem>\n <FormItem {...formItemLayout} labelAlign={labelAlign}\n label=\"Search name:\"\n >\n <Input placeholder=\"Enter a search name:\"/>\n </FormItem>\n </Col>\n </Row>\n <Row>\n <Col style={{ textAlign: 'right' }}>\n <Button type=\"primary\" style={{ marginRight: '5px' }}>Search</Button>\n <Button >Clear All</Button>\n </Col>\n </Row>\n </Form>\n\n\n <Form style={style}>\n <Row gutter=\"4\">\n <Col>\n <FormItem {...formItemLayout} labelAlign={labelAlign}\n label={label}\n required\n >\n <Input placeholder=\"Enter a search name:\"/>\n </FormItem>\n </Col>\n <Col>\n <FormItem {...formItemLayout} labelAlign={labelAlign}\n label=\"Long search name:\"\n >\n <Input placeholder=\"Enter a search name:\"/>\n </FormItem>\n </Col>\n <Col>\n <FormItem {...formItemLayout} labelAlign={labelAlign}\n label=\"Search name:\"\n >\n <Input placeholder=\"Enter a search name:\"/>\n </FormItem>\n </Col>\n <Col>\n <FormItem {...formItemLayout} labelAlign={labelAlign}\n label=\"Search name:\"\n >\n <Input placeholder=\"Enter a search name:\"/>\n </FormItem>\n </Col>\n <Col>\n <FormItem {...formItemLayout} labelAlign={labelAlign}\n label=\"Search name:\"\n >\n <Input placeholder=\"Enter a search name:\"/>\n </FormItem>\n </Col>\n </Row>\n <Row>\n <Col style={{ textAlign: 'right' }}>\n <Button type=\"primary\" style={{ marginRight: '5px' }}>Search</Button>\n <Button >Clear All</Button>\n </Col>\n </Row>\n </Form>\n </div>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
Complex functions can be realized with Field
import { Form, Input, Radio, Field, Button } from '@alifd/next';\n\n\nconst FormItem = Form.Item;\nconst RadioGroup = Radio.Group;\n\nconst formItemLayout = {\n labelCol: {\n span: 6\n },\n wrapperCol: {\n span: 14\n }\n};\n\nclass BasicDemo extends React.Component {\n field = new Field(this);\n\n userExists(rule, value) {\n return new Promise((resolve, reject) => {\n if (!value) {\n resolve();\n } else {\n setTimeout(() => {\n if (value === 'frank') {\n reject([new Error('Sorry, this username is already occupied.')]);\n } else {\n resolve();\n }\n }, 500);\n }\n });\n }\n\n checkPass(rule, value, callback) {\n const { validate } = this.field;\n if (value) {\n validate(['rePasswd']);\n }\n callback();\n }\n\n checkPass2(rule, value, callback) {\n const { getValue } = this.field;\n if (value && value !== getValue('passwd')) {\n return callback('Inconsistent password input twice!');\n } else {\n return callback();\n }\n }\n\n validate = () => {\n this.field.validate(['sex']);\n }\n\n render() {\n const {getState, getValue, getError} = this.field;\n\n return (\n <Form {...formItemLayout} field={this.field}>\n <FormItem\n label=\"Username:\"\n hasFeedback\n required\n validator={this.userExists.bind(this)}\n help={getState('username') === 'loading' ? 'Checking ...' : getError('username')}\n >\n <Input placeholder=\"Input frank\" name=\"username\" />\n <p>Hello {getValue('username')}</p>\n </FormItem>\n\n <FormItem\n label=\"Password:\"\n hasFeedback\n required\n requiredMessage=\"Please enter password\"\n validator={this.checkPass.bind(this)}\n >\n <Input htmlType=\"password\" name=\"passwd\" />\n </FormItem>\n\n <FormItem\n label=\"Check your password:\"\n hasFeedback\n required\n requiredMessage=\"Enter your password again\"\n validator={this.checkPass2.bind(this)}\n >\n <Input htmlType=\"password\" placeholder=\"Enter the same password twice\" name=\"rePasswd\" />\n </FormItem>\n\n <FormItem\n label=\"Gender:\"\n hasFeedback\n required\n requiredMessage=\"Please select your gender\"\n >\n <RadioGroup name=\"sex\" >\n <Radio value=\"male\">Male</Radio>\n <Radio value=\"female\">Female</Radio>\n </RadioGroup>\n </FormItem>\n\n <FormItem wrapperCol={{ offset: 6 }} >\n <Button onClick={this.validate}>Validate by Field</Button>\n <Form.Submit validate type=\"primary\" onClick={(v, e) => console.log(v, e)} style={{margin: '0 10px'}}>Submit</Form.Submit>\n <Form.Reset >Reset</Form.Reset>\n </FormItem>\n </Form>\n );\n }\n}\n\n\nReactDOM.render(<BasicDemo />, mountNode);
配合 Field
可以实现较复杂功能
import { Form, Input, Radio, Field, Button } from '@alifd/next';\n\n\nconst FormItem = Form.Item;\nconst RadioGroup = Radio.Group;\n\nconst formItemLayout = {\n labelCol: {\n span: 6\n },\n wrapperCol: {\n span: 14\n }\n};\n\nclass BasicDemo extends React.Component {\n field = new Field(this);\n\n userExists(rule, value) {\n return new Promise((resolve, reject) => {\n if (!value) {\n resolve();\n } else {\n setTimeout(() => {\n if (value === 'frank') {\n reject([new Error('Sorry, this username is already occupied.')]);\n } else {\n resolve();\n }\n }, 500);\n }\n });\n }\n\n checkPass(rule, value, callback) {\n const { validate } = this.field;\n if (value) {\n validate(['rePasswd']);\n }\n callback();\n }\n\n checkPass2(rule, value, callback) {\n const { getValue } = this.field;\n if (value && value !== getValue('passwd')) {\n return callback('Inconsistent password input twice!');\n } else {\n return callback();\n }\n }\n\n validate = () => {\n this.field.validate(['sex']);\n }\n\n render() {\n const {getState, getValue, getError} = this.field;\n\n return (\n <Form {...formItemLayout} field={this.field}>\n <FormItem\n label=\"Username:\"\n hasFeedback\n required\n validator={this.userExists.bind(this)}\n help={getState('username') === 'loading' ? 'Checking ...' : getError('username')}\n >\n <Input placeholder=\"Input frank\" name=\"username\" />\n <p>Hello {getValue('username')}</p>\n </FormItem>\n\n <FormItem\n label=\"Password:\"\n hasFeedback\n required\n requiredMessage=\"Please enter password\"\n validator={this.checkPass.bind(this)}\n >\n <Input htmlType=\"password\" name=\"passwd\" />\n </FormItem>\n\n <FormItem\n label=\"Check your password:\"\n hasFeedback\n required\n requiredMessage=\"Enter your password again\"\n validator={this.checkPass2.bind(this)}\n >\n <Input htmlType=\"password\" placeholder=\"Enter the same password twice\" name=\"rePasswd\" />\n </FormItem>\n\n <FormItem\n label=\"Gender:\"\n hasFeedback\n required\n requiredMessage=\"Please select your gender\"\n >\n <RadioGroup name=\"sex\" >\n <Radio value=\"male\">Male</Radio>\n <Radio value=\"female\">Female</Radio>\n </RadioGroup>\n </FormItem>\n\n <FormItem wrapperCol={{ offset: 6 }} >\n <Button onClick={this.validate}>Validate by Field</Button>\n <Form.Submit validate type=\"primary\" onClick={(v, e) => console.log(v, e)} style={{margin: '0 10px'}}>Submit</Form.Submit>\n <Form.Reset >Reset</Form.Reset>\n </FormItem>\n </Form>\n );\n }\n}\n\n\nReactDOM.render(<BasicDemo />, mountNode);
import { Form, Input } from '@alifd/next';\n\n\nconst FormItem = Form.Item;\n\nfunction handleSubmit(v) {\n console.log(v);\n}\n\nReactDOM.render(<div>\n <Form inline>\n <FormItem label=\"Username:\">\n <FormItem >\n <Input name=\"first\" style={{width: 80}} placeholder=\"first\"/>\n </FormItem>\n <FormItem >\n <Input name=\"second\" style={{width: 80}} placeholder=\"second\"/>\n </FormItem>\n </FormItem>\n <FormItem label=\"Password:\" required hasFeedback={false}>\n <Input htmlType=\"password\" name=\"inlinePass\" placeholder=\"Please enter your password!\"/>\n </FormItem>\n\n <FormItem label=\" \">\n <Form.Submit onClick={handleSubmit}>Submit</Form.Submit>\n </FormItem>\n </Form>\n</div>, mountNode);
import { Form, Input } from '@alifd/next';\n\n\nconst FormItem = Form.Item;\n\nfunction handleSubmit(v) {\n console.log(v);\n}\n\nReactDOM.render(<div>\n <Form inline>\n <FormItem label=\"Username:\">\n <FormItem >\n <Input name=\"first\" style={{width: 80}} placeholder=\"first\"/>\n </FormItem>\n <FormItem >\n <Input name=\"second\" style={{width: 80}} placeholder=\"second\"/>\n </FormItem>\n </FormItem>\n <FormItem label=\"Password:\" required hasFeedback={false}>\n <Input htmlType=\"password\" name=\"inlinePass\" placeholder=\"Please enter your password!\"/>\n </FormItem>\n\n <FormItem label=\" \">\n <Form.Submit onClick={handleSubmit}>Submit</Form.Submit>\n </FormItem>\n </Form>\n</div>, mountNode);
By setting labelAlign="inset"
(only applicable to Input, Select components, other components do not apply)
import { Form, Input, Select } from '@alifd/next';\n\n\nconst FormItem = Form.Item;\nconst Option = Select.Option;\n\nconst formItemLayout = {\n labelCol: {fixedSpan: 4},\n wrapperCol: {span: 20}\n};\n\nReactDOM.render(<div>\n\n <Form {...formItemLayout} labelAlign=\"inset\" style={{maxWidth: '500px'}}>\n <FormItem label=\"User Name:\">\n <Input placeholder=\"Please enter your name\" id=\"insetUserName\" name=\"insetUserName\"/>\n </FormItem>\n <FormItem label=\"Password:\" validateState=\"error\">\n <Input htmlType=\"password\" placeholder=\"Please enter your password\" id=\"insetPassword\" name=\"insetPassword\"/>\n </FormItem>\n\n <FormItem label=\"Size:\">\n <Select style={{width: '100%'}}>\n <Option value=\"small\">small</Option>\n <Option value=\"medium\">medium</Option>\n <Option value=\"large\">large</Option>\n </Select>\n </FormItem>\n </Form>\n\n <br/><br/>\n\n <Form labelAlign=\"inset\" inline>\n <FormItem label=\"User Name:\">\n <Input placeholder=\"Enter your name\" id=\"insetUserName2\" name=\"insetUserName2\"/>\n </FormItem>\n <FormItem label=\"Password:\" validateState=\"error\" help=\"Password is required!\">\n <Input htmlType=\"password\" placeholder=\"Enter your password\" id=\"insetPassword2\" name=\"insetPassword2\"/>\n </FormItem>\n\n <FormItem label=\"Size:\">\n <Select style={{width: 150}}>\n <Option value=\"small\">small</Option>\n <Option value=\"medium\">medium</Option>\n <Option value=\"large\">large</Option>\n </Select>\n </FormItem>\n </Form>\n</div>, mountNode);
通过设置labelAlign="inset"
(只适用于Input、Select组件,其他组件不适用)
import { Form, Input, Select } from '@alifd/next';\n\n\nconst FormItem = Form.Item;\nconst Option = Select.Option;\n\nconst formItemLayout = {\n labelCol: {fixedSpan: 4},\n wrapperCol: {span: 20}\n};\n\nReactDOM.render(<div>\n\n <Form {...formItemLayout} labelAlign=\"inset\" style={{maxWidth: '500px'}}>\n <FormItem label=\"User Name:\">\n <Input placeholder=\"Please enter your name\" id=\"insetUserName\" name=\"insetUserName\"/>\n </FormItem>\n <FormItem label=\"Password:\" validateState=\"error\">\n <Input htmlType=\"password\" placeholder=\"Please enter your password\" id=\"insetPassword\" name=\"insetPassword\"/>\n </FormItem>\n\n <FormItem label=\"Size:\">\n <Select style={{width: '100%'}}>\n <Option value=\"small\">small</Option>\n <Option value=\"medium\">medium</Option>\n <Option value=\"large\">large</Option>\n </Select>\n </FormItem>\n </Form>\n\n <br/><br/>\n\n <Form labelAlign=\"inset\" inline>\n <FormItem label=\"User Name:\">\n <Input placeholder=\"Enter your name\" id=\"insetUserName2\" name=\"insetUserName2\"/>\n </FormItem>\n <FormItem label=\"Password:\" validateState=\"error\" help=\"Password is required!\">\n <Input htmlType=\"password\" placeholder=\"Enter your password\" id=\"insetPassword2\" name=\"insetPassword2\"/>\n </FormItem>\n\n <FormItem label=\"Size:\">\n <Select style={{width: 150}}>\n <Option value=\"small\">small</Option>\n <Option value=\"medium\">medium</Option>\n <Option value=\"large\">large</Option>\n </Select>\n </FormItem>\n </Form>\n</div>, mountNode);
Display other components related to the Form.
\n","order":"11"},"codes":{"jsx":"import { Form, Input, Button, Checkbox, Radio, Select, Range, Balloon, DatePicker, TimePicker, NumberPicker, Field, Switch, Upload, Grid } from '@alifd/next';\n\n\n\nconst FormItem = Form.Item;\nconst Option = Select.Option;\nconst RangePicker = DatePicker.RangePicker;\nconst {Row, Col} = Grid;\n\nconst formItemLayout = {\n labelCol: {span: 6},\n wrapperCol: {span: 14}\n};\n\nclass Demo extends React.Component {\n field = new Field(this);\n\n handleSubmit(value) {\n console.log('Form values:', value);\n }\n\n render() {\n const init = this.field.init;\n\n return (\n \n );\n }\n}\n\nReactDOM.render(import { Form, Input, Button, Checkbox, Radio, Select, Range, Balloon, DatePicker, TimePicker, NumberPicker, Field, Switch, Upload, Grid } from '@alifd/next';\n\n\n\nconst FormItem = Form.Item;\nconst Option = Select.Option;\nconst RangePicker = DatePicker.RangePicker;\nconst {Row, Col} = Grid;\n\nconst formItemLayout = {\n labelCol: {span: 6},\n wrapperCol: {span: 14}\n};\n\nclass Demo extends React.Component {\n field = new Field(this);\n\n handleSubmit(value) {\n console.log('Form values:', value);\n }\n\n render() {\n const init = this.field.init;\n\n return (\n <Form {...formItemLayout} field={this.field}>\n <FormItem label=\"I'm the title:\">\n <p className=\"next-form-text-align\">The quick brown fox jumps over the lazy dog.</p>\n <p ><a href=\"#\">Link</a></p>\n </FormItem>\n\n <FormItem label=\"Password:\">\n <Balloon trigger={<Input htmlType=\"password\" {...init('pass')} />} align=\"r\" closable={false} triggerType=\"hover\">\n input password\n </Balloon>\n </FormItem>\n\n <FormItem label=\"NumberPicker:\">\n <NumberPicker min={1} max={10} name=\"numberPicker\" defaultValue={3} />\n <span>Something in here</span>\n </FormItem>\n\n <FormItem\n label=\"Switch:\"\n required>\n <Switch name=\"switch\" defaultChecked />\n </FormItem>\n\n <FormItem label=\"Range:\" required>\n <Range defaultValue={30} scales={[0, 100]} marks={[0, 100]} name=\"range\" />\n </FormItem>\n\n <FormItem label=\"Select:\" required>\n <Select style={{width: 200}} name=\"select\">\n <Option value=\"jack\">jack</Option>\n <Option value=\"lucy\">lucy</Option>\n <Option value=\"disabled\" disabled>disabled</Option>\n <Option value=\"hugohua\">hugohua</Option>\n </Select>\n </FormItem>\n\n <FormItem\n label=\"DatePicker:\"\n labelCol={{span: 6}}\n required>\n <Row>\n <FormItem style={{marginRight: 10, marginBottom: 0}}><DatePicker name=\"startDate\"/></FormItem>\n <FormItem style={{marginBottom: 0}}><DatePicker name=\"endDate\" /></FormItem>\n </Row>\n </FormItem>\n\n <FormItem\n label=\"RangePicker:\"\n labelCol={{span: 6}}\n required>\n <RangePicker name=\"rangeDate\"/>\n </FormItem>\n\n <FormItem\n label=\"TimePicker:\"\n required>\n <TimePicker name=\"time\" />\n </FormItem>\n\n <FormItem\n label=\"Checkbox:\">\n <Checkbox.Group name=\"checkbox\">\n <Checkbox value=\"a\">option 1 </Checkbox>\n <Checkbox value=\"b\">option 2 </Checkbox>\n <Checkbox disabled value=\"c\">option 3(disabled)</Checkbox>\n </Checkbox.Group>\n </FormItem>\n\n <FormItem\n label=\"Radio:\">\n <Radio.Group name=\"radio\">\n <Radio value=\"apple\">apple</Radio>\n <Radio value=\"banana\">banana</Radio>\n <Radio disabled value=\"cherry\">cherry(disabled)</Radio>\n </Radio.Group>\n </FormItem>\n\n <FormItem\n label=\"Logo:\"\n >\n <Upload action=\"/upload.do\" listType=\"text\" name=\"upload\" >\n <Button type=\"primary\" style={{margin: '0 0 10px'}}>Upload</Button>\n </Upload>\n </FormItem>\n <Row style={{marginTop: 24}}>\n <Col offset=\"6\">\n <Form.Submit type=\"primary\" onClick={this.handleSubmit.bind(this)}>Submit</Form.Submit>\n </Col>\n </Row>\n </Form>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
展示和表单相关的其他组件。
\n","order":"11"},"codes":{"jsx":"import { Form, Input, Button, Checkbox, Radio, Select, Range, Balloon, DatePicker, TimePicker, NumberPicker, Field, Switch, Upload, Grid } from '@alifd/next';\n\n\n\nconst FormItem = Form.Item;\nconst Option = Select.Option;\nconst RangePicker = DatePicker.RangePicker;\nconst {Row, Col} = Grid;\n\nconst formItemLayout = {\n labelCol: {span: 6},\n wrapperCol: {span: 14}\n};\n\nclass Demo extends React.Component {\n field = new Field(this);\n\n handleSubmit(value) {\n console.log('Form values:', value);\n }\n\n render() {\n const init = this.field.init;\n\n return (\n \n );\n }\n}\n\nReactDOM.render(import { Form, Input, Button, Checkbox, Radio, Select, Range, Balloon, DatePicker, TimePicker, NumberPicker, Field, Switch, Upload, Grid } from '@alifd/next';\n\n\n\nconst FormItem = Form.Item;\nconst Option = Select.Option;\nconst RangePicker = DatePicker.RangePicker;\nconst {Row, Col} = Grid;\n\nconst formItemLayout = {\n labelCol: {span: 6},\n wrapperCol: {span: 14}\n};\n\nclass Demo extends React.Component {\n field = new Field(this);\n\n handleSubmit(value) {\n console.log('Form values:', value);\n }\n\n render() {\n const init = this.field.init;\n\n return (\n <Form {...formItemLayout} field={this.field}>\n <FormItem label=\"I'm the title:\">\n <p className=\"next-form-text-align\">The quick brown fox jumps over the lazy dog.</p>\n <p ><a href=\"#\">Link</a></p>\n </FormItem>\n\n <FormItem label=\"Password:\">\n <Balloon trigger={<Input htmlType=\"password\" {...init('pass')} />} align=\"r\" closable={false} triggerType=\"hover\">\n input password\n </Balloon>\n </FormItem>\n\n <FormItem label=\"NumberPicker:\">\n <NumberPicker min={1} max={10} name=\"numberPicker\" defaultValue={3} />\n <span>Something in here</span>\n </FormItem>\n\n <FormItem\n label=\"Switch:\"\n required>\n <Switch name=\"switch\" defaultChecked />\n </FormItem>\n\n <FormItem label=\"Range:\" required>\n <Range defaultValue={30} scales={[0, 100]} marks={[0, 100]} name=\"range\" />\n </FormItem>\n\n <FormItem label=\"Select:\" required>\n <Select style={{width: 200}} name=\"select\">\n <Option value=\"jack\">jack</Option>\n <Option value=\"lucy\">lucy</Option>\n <Option value=\"disabled\" disabled>disabled</Option>\n <Option value=\"hugohua\">hugohua</Option>\n </Select>\n </FormItem>\n\n <FormItem\n label=\"DatePicker:\"\n labelCol={{span: 6}}\n required>\n <Row>\n <FormItem style={{marginRight: 10, marginBottom: 0}}><DatePicker name=\"startDate\"/></FormItem>\n <FormItem style={{marginBottom: 0}}><DatePicker name=\"endDate\" /></FormItem>\n </Row>\n </FormItem>\n\n <FormItem\n label=\"RangePicker:\"\n labelCol={{span: 6}}\n required>\n <RangePicker name=\"rangeDate\"/>\n </FormItem>\n\n <FormItem\n label=\"TimePicker:\"\n required>\n <TimePicker name=\"time\" />\n </FormItem>\n\n <FormItem\n label=\"Checkbox:\">\n <Checkbox.Group name=\"checkbox\">\n <Checkbox value=\"a\">option 1 </Checkbox>\n <Checkbox value=\"b\">option 2 </Checkbox>\n <Checkbox disabled value=\"c\">option 3(disabled)</Checkbox>\n </Checkbox.Group>\n </FormItem>\n\n <FormItem\n label=\"Radio:\">\n <Radio.Group name=\"radio\">\n <Radio value=\"apple\">apple</Radio>\n <Radio value=\"banana\">banana</Radio>\n <Radio disabled value=\"cherry\">cherry(disabled)</Radio>\n </Radio.Group>\n </FormItem>\n\n <FormItem\n label=\"Logo:\"\n >\n <Upload action=\"/upload.do\" listType=\"text\" name=\"upload\" >\n <Button type=\"primary\" style={{margin: '0 0 10px'}}>Upload</Button>\n </Upload>\n </FormItem>\n <Row style={{marginTop: 24}}>\n <Col offset=\"6\">\n <Form.Submit type=\"primary\" onClick={this.handleSubmit.bind(this)}>Submit</Form.Submit>\n </Col>\n </Row>\n </Form>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
force set labelAlign=top while device=phone
\n","order":"17"},"codes":{"jsx":"import { Form, Input, Checkbox, Switch, Radio } from '@alifd/next';\n\n\nconst FormItem = Form.Item;\n\nconst formItemLayout = {\n labelCol: {\n fixedSpan: 10\n },\n wrapperCol: {\n span: 14\n }\n};\n\nclass Demo extends React.Component {\n state = {\n device: 'desktop'\n }\n\n handleDeviceChange = (device) => {\n this.setState({\n device\n });\n };\n\n render() {\n return (\nimport { Form, Input, Checkbox, Switch, Radio } from '@alifd/next';\n\n\nconst FormItem = Form.Item;\n\nconst formItemLayout = {\n labelCol: {\n fixedSpan: 10\n },\n wrapperCol: {\n span: 14\n }\n};\n\nclass Demo extends React.Component {\n state = {\n device: 'desktop'\n }\n\n handleDeviceChange = (device) => {\n this.setState({\n device\n });\n };\n\n render() {\n return (\n <div>\n <Radio.Group\n shape=\"button\"\n value={this.state.device}\n onChange={this.handleDeviceChange}\n >\n <Radio value=\"desktop\">desktop</Radio>\n <Radio value=\"phone\">phone</Radio>\n </Radio.Group>\n <hr/>\n <Form style={{width: '60%'}} {...formItemLayout} device={this.state.device}>\n <FormItem label=\"Username:\">\n <p>Fixed Name</p>\n </FormItem>\n <FormItem label=\"password:\">\n <Input htmlType=\"password\" name=\"basePass\" placeholder=\"Please Enter Password\"/>\n </FormItem>\n <FormItem label=\"Note:\" help=\"something\">\n <Input.TextArea placeholder=\"something\" name=\"baseRemark\" />\n </FormItem>\n <FormItem label=\"Agreement:\">\n <Checkbox name=\"baseAgreement\" defaultChecked>Agree</Checkbox>\n </FormItem>\n <FormItem label=\" \">\n <Form.Submit >Confirm</Form.Submit>\n </FormItem>\n </Form>\n </div>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
device=phone 下会强制设置 labelAlign=top
\n","order":"17"},"codes":{"jsx":"import { Form, Input, Checkbox, Switch, Radio } from '@alifd/next';\n\n\nconst FormItem = Form.Item;\n\nconst formItemLayout = {\n labelCol: {\n fixedSpan: 10\n },\n wrapperCol: {\n span: 14\n }\n};\n\nclass Demo extends React.Component {\n state = {\n device: 'desktop'\n }\n\n handleDeviceChange = (device) => {\n this.setState({\n device\n });\n };\n\n render() {\n return (\nimport { Form, Input, Checkbox, Switch, Radio } from '@alifd/next';\n\n\nconst FormItem = Form.Item;\n\nconst formItemLayout = {\n labelCol: {\n fixedSpan: 10\n },\n wrapperCol: {\n span: 14\n }\n};\n\nclass Demo extends React.Component {\n state = {\n device: 'desktop'\n }\n\n handleDeviceChange = (device) => {\n this.setState({\n device\n });\n };\n\n render() {\n return (\n <div>\n <Radio.Group\n shape=\"button\"\n value={this.state.device}\n onChange={this.handleDeviceChange}\n >\n <Radio value=\"desktop\">desktop</Radio>\n <Radio value=\"phone\">phone</Radio>\n </Radio.Group>\n <hr/>\n <Form style={{width: '60%'}} {...formItemLayout} device={this.state.device}>\n <FormItem label=\"Username:\">\n <p>Fixed Name</p>\n </FormItem>\n <FormItem label=\"password:\">\n <Input htmlType=\"password\" name=\"basePass\" placeholder=\"Please Enter Password\"/>\n </FormItem>\n <FormItem label=\"Note:\" help=\"something\">\n <Input.TextArea placeholder=\"something\" name=\"baseRemark\" />\n </FormItem>\n <FormItem label=\"Agreement:\">\n <Checkbox name=\"baseAgreement\" defaultChecked>Agree</Checkbox>\n </FormItem>\n <FormItem label=\" \">\n <Form.Submit >Confirm</Form.Submit>\n </FormItem>\n </Form>\n </div>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
FormItem Nest
\n","order":"5"},"codes":{"jsx":"import { Form, Input, Grid } from '@alifd/next';\n\n\n\nconst FormItem = Form.Item;\nconst {Row, Col} = Grid;\n\nconst formItemLayout = {\n labelCol: {span: 4},\n wrapperCol: {span: 14}\n};\n\nconst insetLayout = {\n labelCol: {fixedSpan: 3}\n};\n\nReactDOM.render(, mountNode);\n"},"body":"\n````jsx\nimport { Form, Input, Grid } from '@alifd/next';\n\n\n\nconst FormItem = Form.Item;\nconst {Row, Col} = Grid;\n\nconst formItemLayout = {\n labelCol: {span: 4},\n wrapperCol: {span: 14}\n};\n\nconst insetLayout = {\n labelCol: {fixedSpan: 3}\n};\n\nReactDOM.render(, mountNode);\n````","html":"import { Form, Input, Grid } from '@alifd/next';\n\n\n\nconst FormItem = Form.Item;\nconst {Row, Col} = Grid;\n\nconst formItemLayout = {\n labelCol: {span: 4},\n wrapperCol: {span: 14}\n};\n\nconst insetLayout = {\n labelCol: {fixedSpan: 3}\n};\n\nReactDOM.render(<Form {...formItemLayout}>\n <FormItem id=\"control-input\" label=\"Input Something:\">\n <Row gutter=\"4\">\n <Col>\n <FormItem label=\"Nest\" labelAlign=\"inset\" {...insetLayout} required requiredTrigger=\"onBlur\" asterisk={false}>\n <Input placeholder=\"Please enter...\" name=\"firstname\"/>\n </FormItem>\n </Col>\n <Col>\n <FormItem label=\"Nest\" labelAlign=\"inset\" {...insetLayout} required asterisk={false}>\n <Input placeholder=\"need onChange\" name=\"secondname\" />\n </FormItem>\n </Col>\n </Row>\n </FormItem>\n <FormItem label=\"Bank Account:\" >\n <Row gutter=\"4\">\n <Col>\n <FormItem required requiredTrigger=\"onBlur\">\n <Input name=\"A\"/>\n </FormItem>\n </Col>\n <Col>\n <FormItem required requiredTrigger=\"onBlur\">\n <Input name=\"B\"/>\n </FormItem>\n </Col>\n <Col>\n <FormItem required requiredTrigger=\"onBlur\">\n <Input name=\"C\"/>\n </FormItem>\n </Col>\n <Col>\n <FormItem required requiredTrigger=\"onBlur\">\n <Input name=\"D\"/>\n </FormItem>\n </Col>\n </Row>\n </FormItem>\n <FormItem label=\" \">\n <Form.Submit onClick={(v) => console.log(v)}>Submit</Form.Submit>\n </FormItem>\n</Form>, mountNode);
FormItem 嵌套
\n","order":"5"},"codes":{"jsx":"import { Form, Input, Grid } from '@alifd/next';\n\n\n\nconst FormItem = Form.Item;\nconst {Row, Col} = Grid;\n\nconst formItemLayout = {\n labelCol: {span: 4},\n wrapperCol: {span: 14}\n};\n\nconst insetLayout = {\n labelCol: {fixedSpan: 3}\n};\n\nReactDOM.render(, mountNode);\n"},"body":"\n\n````jsx\nimport { Form, Input, Grid } from '@alifd/next';\n\n\n\nconst FormItem = Form.Item;\nconst {Row, Col} = Grid;\n\nconst formItemLayout = {\n labelCol: {span: 4},\n wrapperCol: {span: 14}\n};\n\nconst insetLayout = {\n labelCol: {fixedSpan: 3}\n};\n\nReactDOM.render(, mountNode);\n````","html":"import { Form, Input, Grid } from '@alifd/next';\n\n\n\nconst FormItem = Form.Item;\nconst {Row, Col} = Grid;\n\nconst formItemLayout = {\n labelCol: {span: 4},\n wrapperCol: {span: 14}\n};\n\nconst insetLayout = {\n labelCol: {fixedSpan: 3}\n};\n\nReactDOM.render(<Form {...formItemLayout}>\n <FormItem id=\"control-input\" label=\"Input Something:\">\n <Row gutter=\"4\">\n <Col>\n <FormItem label=\"Nest\" labelAlign=\"inset\" {...insetLayout} required requiredTrigger=\"onBlur\" asterisk={false}>\n <Input placeholder=\"Please enter...\" name=\"firstname\"/>\n </FormItem>\n </Col>\n <Col>\n <FormItem label=\"Nest\" labelAlign=\"inset\" {...insetLayout} required asterisk={false}>\n <Input placeholder=\"need onChange\" name=\"secondname\" />\n </FormItem>\n </Col>\n </Row>\n </FormItem>\n <FormItem label=\"Bank Account:\" >\n <Row gutter=\"4\">\n <Col>\n <FormItem required requiredTrigger=\"onBlur\">\n <Input name=\"A\"/>\n </FormItem>\n </Col>\n <Col>\n <FormItem required requiredTrigger=\"onBlur\">\n <Input name=\"B\"/>\n </FormItem>\n </Col>\n <Col>\n <FormItem required requiredTrigger=\"onBlur\">\n <Input name=\"C\"/>\n </FormItem>\n </Col>\n <Col>\n <FormItem required requiredTrigger=\"onBlur\">\n <Input name=\"D\"/>\n </FormItem>\n </Col>\n </Row>\n </FormItem>\n <FormItem label=\" \">\n <Form.Submit onClick={(v) => console.log(v)}>Submit</Form.Submit>\n </FormItem>\n</Form>, mountNode);
Requires htmlType="submit" element in Form
\n","order":"7"},"codes":{"jsx":"import { Form, Input } from '@alifd/next';\n\n\nconst FormItem = Form.Item;\n\nclass Demo extends React.Component {\n onSubmit(e) {\n e.preventDefault(); // form will auto submit if remove this line\n console.log('onsubmit');\n }\n\n render() {\n return (\nimport { Form, Input } from '@alifd/next';\n\n\nconst FormItem = Form.Item;\n\nclass Demo extends React.Component {\n onSubmit(e) {\n e.preventDefault(); // form will auto submit if remove this line\n console.log('onsubmit');\n }\n\n render() {\n return (\n <Form onSubmit={this.onSubmit.bind(this)}>\n <FormItem >\n <Input placeholder=\"Enter Key can also trigger ‘onSubmit’\"/>\n </FormItem>\n <Form.Submit htmlType=\"submit\">submit</Form.Submit>\n </Form>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
需要Form里面有 htmlType="submit" 的元素
\n","order":"7"},"codes":{"jsx":"import { Form, Input } from '@alifd/next';\n\n\nconst FormItem = Form.Item;\n\nclass Demo extends React.Component {\n onSubmit(e) {\n e.preventDefault(); // form will auto submit if remove this line\n console.log('onsubmit');\n }\n\n render() {\n return (\nimport { Form, Input } from '@alifd/next';\n\n\nconst FormItem = Form.Item;\n\nclass Demo extends React.Component {\n onSubmit(e) {\n e.preventDefault(); // form will auto submit if remove this line\n console.log('onsubmit');\n }\n\n render() {\n return (\n <Form onSubmit={this.onSubmit.bind(this)}>\n <FormItem >\n <Input placeholder=\"Enter Key can also trigger ‘onSubmit’\"/>\n </FormItem>\n <Form.Submit htmlType=\"submit\">submit</Form.Submit>\n </Form>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
Combine componentWillReceiveProps
with setErrorsin
redux`
If you need to specify the error message position, you can make help=""
and place the error display yourself.
{this.field.getError('username')}
\nemail: {this.props.email && this.props.email.value}
\n \n \n \n \n \n );\n }\n}\n\n\nconst ReduxFormDemo = connect((state) => {\n return {\n formData: state.formReducer\n };\n})(FormDemo);\n\nconst store = createStore(combineReducers({\n formReducer\n}));\n\nReactDOM.render({this.field.getError('username')}
\nemail: {this.props.email && this.props.email.value}
\n \n \n \n \n \n );\n }\n}\n\n\nconst ReduxFormDemo = connect((state) => {\n return {\n formData: state.formReducer\n };\n})(FormDemo);\n\nconst store = createStore(combineReducers({\n formReducer\n}));\n\nReactDOM.render(import { Form, Input, Button, Field } from '@alifd/next';\nimport { combineReducers, createStore } from 'redux';\nimport { Provider, connect } from 'react-redux';\n\n\n\nconst initState = {\n values: {email: '', username: 'xiachi'},\n errors: {}\n};\n\nfunction formReducer(state = initState, action) {\n switch (action.type) {\n case 'save_fields':\n return {\n ...state,\n values: {\n ...state.values,\n ...action.values\n }\n };\n case 'set_errors':\n return {\n ...state,\n errors: {\n ...state.errors,\n ...action.errors\n }\n };\n default:\n return state;\n }\n}\n\nclass FormDemo extends React.Component {\n constructor(props) {\n super(props);\n\n this.field = new Field(this, {\n onChange: (name, value) => {\n console.log('onChange', name, value, this.field.getError(name));\n this.props.dispatch({\n type: 'save_fields',\n values: {\n [name]: value\n }\n });\n this.props.dispatch({\n type: 'set_errors',\n errors: {\n [name]: this.field.getError(name)\n }\n });\n }\n });\n }\n\n componentWillReceiveProps(nextProps) {\n this.field.setValues(nextProps.formData.values);\n this.field.setErrors(nextProps.formData.errors);\n }\n\n setEmail() {\n this.props.dispatch({\n type: 'save_fields',\n values: {\n email: 'qq@gmail.com'\n }\n });\n }\n\n setName() {\n this.props.dispatch({\n type: 'save_fields',\n values: {\n username: 'frank'\n }\n });\n }\n\n setError() {\n this.props.dispatch({\n type: 'set_errors',\n errors: {\n email: 'Error message from remote'\n }\n });\n }\n\n setErrors() {\n this.props.dispatch({\n type: 'set_errors',\n errors: {\n email: 'A-Error message from remote',\n username: 'B-Error message from remote'\n }\n });\n }\n\n render() {\n return (<Form field={this.field}>\n <Form.Item required format=\"email\">\n <Input name=\"email\"/>\n </Form.Item>\n <Form.Item help=\"\" required requiredMessage=\"required\">\n <Input name=\"username\" defaultValue={this.props.formData.values.username} />\n <p style={{color: 'blue'}}>{this.field.getError('username')}</p>\n </Form.Item>\n\n <p>email: {this.props.email && this.props.email.value}</p>\n <Button onClick={this.setEmail.bind(this)}>setEmail</Button>\n <Button onClick={this.setName.bind(this)}>setName</Button>\n <Button onClick={this.setError.bind(this)}>setError</Button>\n <Button onClick={this.setErrors.bind(this)}>setErrors</Button>\n <Button onClick={() => this.field.reset()}>reset</Button>\n </Form>);\n }\n}\n\n\nconst ReduxFormDemo = connect((state) => {\n return {\n formData: state.formReducer\n };\n})(FormDemo);\n\nconst store = createStore(combineReducers({\n formReducer\n}));\n\nReactDOM.render(<Provider store={store}>\n <div>\n <ReduxFormDemo />\n </div>\n</Provider>, mountNode);
在redux
中结合 componentWillReceiveProps
setErrors
使用, 配合 Field 使用更加方便
如果需要自己控制错误位置,可以让help=""
然后自己放置展示错误的地方
{this.field.getError('username')}
\nemail: {this.props.email && this.props.email.value}
\n \n \n \n \n \n );\n }\n}\n\n\nconst ReduxFormDemo = connect((state) => {\n return {\n formData: state.formReducer\n };\n})(FormDemo);\n\nconst store = createStore(combineReducers({\n formReducer\n}));\n\nReactDOM.render({this.field.getError('username')}
\nemail: {this.props.email && this.props.email.value}
\n \n \n \n \n \n );\n }\n}\n\n\nconst ReduxFormDemo = connect((state) => {\n return {\n formData: state.formReducer\n };\n})(FormDemo);\n\nconst store = createStore(combineReducers({\n formReducer\n}));\n\nReactDOM.render(import { Form, Input, Button, Field } from '@alifd/next';\nimport { combineReducers, createStore } from 'redux';\nimport { Provider, connect } from 'react-redux';\n\n\n\nconst initState = {\n values: {email: '', username: 'xiachi'},\n errors: {}\n};\n\nfunction formReducer(state = initState, action) {\n switch (action.type) {\n case 'save_fields':\n return {\n ...state,\n values: {\n ...state.values,\n ...action.values\n }\n };\n case 'set_errors':\n return {\n ...state,\n errors: {\n ...state.errors,\n ...action.errors\n }\n };\n default:\n return state;\n }\n}\n\nclass FormDemo extends React.Component {\n constructor(props) {\n super(props);\n\n this.field = new Field(this, {\n onChange: (name, value) => {\n console.log('onChange', name, value, this.field.getError(name));\n this.props.dispatch({\n type: 'save_fields',\n values: {\n [name]: value\n }\n });\n this.props.dispatch({\n type: 'set_errors',\n errors: {\n [name]: this.field.getError(name)\n }\n });\n }\n });\n }\n\n componentWillReceiveProps(nextProps) {\n this.field.setValues(nextProps.formData.values);\n this.field.setErrors(nextProps.formData.errors);\n }\n\n setEmail() {\n this.props.dispatch({\n type: 'save_fields',\n values: {\n email: 'qq@gmail.com'\n }\n });\n }\n\n setName() {\n this.props.dispatch({\n type: 'save_fields',\n values: {\n username: 'frank'\n }\n });\n }\n\n setError() {\n this.props.dispatch({\n type: 'set_errors',\n errors: {\n email: 'Error message from remote'\n }\n });\n }\n\n setErrors() {\n this.props.dispatch({\n type: 'set_errors',\n errors: {\n email: 'A-Error message from remote',\n username: 'B-Error message from remote'\n }\n });\n }\n\n render() {\n return (<Form field={this.field}>\n <Form.Item required format=\"email\">\n <Input name=\"email\"/>\n </Form.Item>\n <Form.Item help=\"\" required requiredMessage=\"required\">\n <Input name=\"username\" defaultValue={this.props.formData.values.username} />\n <p style={{color: 'blue'}}>{this.field.getError('username')}</p>\n </Form.Item>\n\n <p>email: {this.props.email && this.props.email.value}</p>\n <Button onClick={this.setEmail.bind(this)}>setEmail</Button>\n <Button onClick={this.setName.bind(this)}>setName</Button>\n <Button onClick={this.setError.bind(this)}>setError</Button>\n <Button onClick={this.setErrors.bind(this)}>setErrors</Button>\n <Button onClick={() => this.field.reset()}>reset</Button>\n </Form>);\n }\n}\n\n\nconst ReduxFormDemo = connect((state) => {\n return {\n formData: state.formReducer\n };\n})(FormDemo);\n\nconst store = createStore(combineReducers({\n formReducer\n}));\n\nReactDOM.render(<Provider store={store}>\n <div>\n <ReduxFormDemo />\n </div>\n</Provider>, mountNode);
Using in redux
with componentWillReceiveProps
setValues
email: {this.props.email && this.props.email.value}
\n \n \n \n );\n }\n}\n\nconst ReduxFormDemo = connect((state) => {\n return {\n formData: state.formReducer\n };\n})(FormDemo);\n\nconst store = createStore(combineReducers({\n formReducer\n}));\n\nReactDOM.render(email: {this.props.email && this.props.email.value}
\n \n \n \n );\n }\n}\n\nconst ReduxFormDemo = connect((state) => {\n return {\n formData: state.formReducer\n };\n})(FormDemo);\n\nconst store = createStore(combineReducers({\n formReducer\n}));\n\nReactDOM.render(import { Form, Input, Button, Checkbox, Field } from '@alifd/next';\nimport { combineReducers, createStore } from 'redux';\nimport { Provider, connect } from 'react-redux';\n\n\n\n\nconst CheckboxGroup = Checkbox.Group;\nfunction formReducer(state = {email: '', username: 'xiachi', fruit: ['apple']}, action) {\n switch (action.type) {\n case 'save_fields':\n return {\n ...state,\n ...action.payload\n };\n default:\n return state;\n }\n}\n\nclass FormDemo extends React.Component {\n constructor(props) {\n super(props);\n this.field = new Field(this, {\n onChange: (name, value) => {\n console.log('onChange', name, value, this.field.getValues());\n this.props.dispatch({\n type: 'save_fields',\n payload: {\n [name]: value\n }\n });\n /* Method 2, Updates all values.\n this.props.dispatch({\n type: 'save_fields',\n payload: this.field.getValues()\n });\n */\n }\n });\n }\n\n componentWillReceiveProps(nextProps) {\n this.field.setValues(nextProps.formData);\n }\n\n setEmail() {\n this.props.dispatch({\n type: 'save_fields',\n payload: {\n email: 'qq@gmail.com'\n }\n });\n }\n\n setName() {\n this.props.dispatch({\n type: 'save_fields',\n payload: {\n username: 'frank'\n }\n });\n }\n\n setGroup() {\n this.props.dispatch({\n type: 'save_fields',\n payload: {\n fruit: ['pear']\n }\n });\n }\n\n render() {\n return (<Form field={this.field}>\n <Form.Item required requiredMessage=\"required!\">\n <Input name=\"email\"/>\n </Form.Item>\n <Form.Item required requiredMessage=\"required!\">\n <Input name=\"username\" defaultValue={this.props.formData.username} />\n </Form.Item>\n <Form.Item required requiredMessage=\"required!\">\n <CheckboxGroup name=\"fruit\" dataSource={[{label: 'Apple', value: 'apple'}, {label: 'Pear', value: 'pear'}]} defaultValue={this.props.formData.fruit}/>\n </Form.Item>\n\n <p>email: {this.props.email && this.props.email.value}</p>\n <Button onClick={this.setEmail.bind(this)}>setEmail</Button>\n <Button onClick={this.setName.bind(this)}>setName</Button>\n <Button onClick={this.setGroup.bind(this)}>setGroup</Button>\n </Form>);\n }\n}\n\nconst ReduxFormDemo = connect((state) => {\n return {\n formData: state.formReducer\n };\n})(FormDemo);\n\nconst store = createStore(combineReducers({\n formReducer\n}));\n\nReactDOM.render(<Provider store={store}>\n <div>\n <ReduxFormDemo />\n </div>\n</Provider>, mountNode);
在redux
中结合 componentWillReceiveProps
setValues
使用, 配合 Field 使用
email: {this.props.email && this.props.email.value}
\n \n \n \n );\n }\n}\n\nconst ReduxFormDemo = connect((state) => {\n return {\n formData: state.formReducer\n };\n})(FormDemo);\n\nconst store = createStore(combineReducers({\n formReducer\n}));\n\nReactDOM.render(email: {this.props.email && this.props.email.value}
\n \n \n \n );\n }\n}\n\nconst ReduxFormDemo = connect((state) => {\n return {\n formData: state.formReducer\n };\n})(FormDemo);\n\nconst store = createStore(combineReducers({\n formReducer\n}));\n\nReactDOM.render(import { Form, Input, Button, Checkbox, Field } from '@alifd/next';\nimport { combineReducers, createStore } from 'redux';\nimport { Provider, connect } from 'react-redux';\n\n\n\n\nconst CheckboxGroup = Checkbox.Group;\nfunction formReducer(state = {email: '', username: 'xiachi', fruit: ['apple']}, action) {\n switch (action.type) {\n case 'save_fields':\n return {\n ...state,\n ...action.payload\n };\n default:\n return state;\n }\n}\n\nclass FormDemo extends React.Component {\n constructor(props) {\n super(props);\n this.field = new Field(this, {\n onChange: (name, value) => {\n console.log('onChange', name, value, this.field.getValues());\n this.props.dispatch({\n type: 'save_fields',\n payload: {\n [name]: value\n }\n });\n /* Method 2, Updates all values.\n this.props.dispatch({\n type: 'save_fields',\n payload: this.field.getValues()\n });\n */\n }\n });\n }\n\n componentWillReceiveProps(nextProps) {\n this.field.setValues(nextProps.formData);\n }\n\n setEmail() {\n this.props.dispatch({\n type: 'save_fields',\n payload: {\n email: 'qq@gmail.com'\n }\n });\n }\n\n setName() {\n this.props.dispatch({\n type: 'save_fields',\n payload: {\n username: 'frank'\n }\n });\n }\n\n setGroup() {\n this.props.dispatch({\n type: 'save_fields',\n payload: {\n fruit: ['pear']\n }\n });\n }\n\n render() {\n return (<Form field={this.field}>\n <Form.Item required requiredMessage=\"required!\">\n <Input name=\"email\"/>\n </Form.Item>\n <Form.Item required requiredMessage=\"required!\">\n <Input name=\"username\" defaultValue={this.props.formData.username} />\n </Form.Item>\n <Form.Item required requiredMessage=\"required!\">\n <CheckboxGroup name=\"fruit\" dataSource={[{label: 'Apple', value: 'apple'}, {label: 'Pear', value: 'pear'}]} defaultValue={this.props.formData.fruit}/>\n </Form.Item>\n\n <p>email: {this.props.email && this.props.email.value}</p>\n <Button onClick={this.setEmail.bind(this)}>setEmail</Button>\n <Button onClick={this.setName.bind(this)}>setName</Button>\n <Button onClick={this.setGroup.bind(this)}>setGroup</Button>\n </Form>);\n }\n}\n\nconst ReduxFormDemo = connect((state) => {\n return {\n formData: state.formReducer\n };\n})(FormDemo);\n\nconst store = createStore(combineReducers({\n formReducer\n}));\n\nReactDOM.render(<Provider store={store}>\n <div>\n <ReduxFormDemo />\n </div>\n</Provider>, mountNode);
send code
\n","order":"10"},"codes":{"jsx":"import { Form, Input } from '@alifd/next';\n\n\nconst FormItem = Form.Item;\n\nconst formItemLayout = {\n labelCol: { fixedSpan: 3 },\n wrapperCol: { span: 20 }\n};\n\nclass Demo extends React.Component {\n state = {\n code: '',\n second: 60\n }\n\n handleSubmit = (values, errors) => {\n if (errors) {\n return;\n }\n console.log('Get form value:', values);\n };\n\n sendCode = (values, errors) => {\n if (errors) {\n return;\n }\n this.setState({\n code: Math.floor(Math.random() * (999999 - 99999 + 1) + 99999)\n });\n\n setInterval(() => {\n this.setState({\n second: --this.state.second\n });\n }, 1000);\n }\n\n render() {\n const { code } = this.state;\n\n return (\n \n );\n }\n}\n\nReactDOM.render(import { Form, Input } from '@alifd/next';\n\n\nconst FormItem = Form.Item;\n\nconst formItemLayout = {\n labelCol: { fixedSpan: 3 },\n wrapperCol: { span: 20 }\n};\n\nclass Demo extends React.Component {\n state = {\n code: '',\n second: 60\n }\n\n handleSubmit = (values, errors) => {\n if (errors) {\n return;\n }\n console.log('Get form value:', values);\n };\n\n sendCode = (values, errors) => {\n if (errors) {\n return;\n }\n this.setState({\n code: Math.floor(Math.random() * (999999 - 99999 + 1) + 99999)\n });\n\n setInterval(() => {\n this.setState({\n second: --this.state.second\n });\n }, 1000);\n }\n\n render() {\n const { code } = this.state;\n\n return (\n <Form style={{ width: 400 }} {...formItemLayout} labelTextAlign=\"left\" size=\"large\" labelAlign=\"inset\" >\n <FormItem label=\"name\" required asterisk={false}>\n <Input name=\"username\" trim defaultValue=\"frank\" />\n </FormItem>\n <FormItem label=\"phone\" format=\"tel\" required asterisk={false}>\n <Input name=\"phone\" trim innerAfter={\n <Form.Submit\n text\n type=\"primary\"\n disabled={!!code}\n validate={['phone']}\n onClick={this.sendCode}\n style={{ marginRight: 10 }}\n >\n {code ? `retry after ${this.state.second}s` : 'send code'}\n </Form.Submit>\n } />\n </FormItem>\n {\n this.state.code ? <FormItem label=\"code\" required asterisk={false}>\n <Input name=\"code\" trim defaultValue={this.state.code} />\n </FormItem> : null\n }\n\n <FormItem label=\" \">\n <Form.Submit style={{ width: '100%' }} type=\"primary\" validate onClick={this.handleSubmit}>Submit</Form.Submit>\n </FormItem>\n </Form>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
验证码获取
\n","order":"1"},"codes":{"jsx":"import { Form, Input } from '@alifd/next';\n\n\nconst FormItem = Form.Item;\n\nconst formItemLayout = {\n labelCol: { fixedSpan: 3 },\n wrapperCol: { span: 20 }\n};\n\nclass Demo extends React.Component {\n state = {\n code: '',\n second: 60\n }\n\n handleSubmit = (values, errors) => {\n if (errors) {\n return;\n }\n console.log('Get form value:', values);\n };\n\n sendCode = (values, errors) => {\n if (errors) {\n return;\n }\n this.setState({\n code: Math.floor(Math.random() * (999999 - 99999 + 1) + 99999)\n });\n\n setInterval(() => {\n this.setState({\n second: --this.state.second\n });\n }, 1000);\n }\n\n render() {\n const { code } = this.state;\n\n return (\n \n );\n }\n}\n\nReactDOM.render(import { Form, Input } from '@alifd/next';\n\n\nconst FormItem = Form.Item;\n\nconst formItemLayout = {\n labelCol: { fixedSpan: 3 },\n wrapperCol: { span: 20 }\n};\n\nclass Demo extends React.Component {\n state = {\n code: '',\n second: 60\n }\n\n handleSubmit = (values, errors) => {\n if (errors) {\n return;\n }\n console.log('Get form value:', values);\n };\n\n sendCode = (values, errors) => {\n if (errors) {\n return;\n }\n this.setState({\n code: Math.floor(Math.random() * (999999 - 99999 + 1) + 99999)\n });\n\n setInterval(() => {\n this.setState({\n second: --this.state.second\n });\n }, 1000);\n }\n\n render() {\n const { code } = this.state;\n\n return (\n <Form style={{ width: 400 }} {...formItemLayout} labelTextAlign=\"left\" size=\"large\" labelAlign=\"inset\" >\n <FormItem label=\"name\" required asterisk={false}>\n <Input name=\"username\" trim defaultValue=\"frank\" />\n </FormItem>\n <FormItem label=\"phone\" format=\"tel\" required asterisk={false}>\n <Input name=\"phone\" trim innerAfter={\n <Form.Submit\n text\n type=\"primary\"\n disabled={!!code}\n validate={['phone']}\n onClick={this.sendCode}\n style={{ marginRight: 10 }}\n >\n {code ? `retry after ${this.state.second}s` : 'send code'}\n </Form.Submit>\n } />\n </FormItem>\n {\n this.state.code ? <FormItem label=\"code\" required asterisk={false}>\n <Input name=\"code\" trim defaultValue={this.state.code} />\n </FormItem> : null\n }\n\n <FormItem label=\" \">\n <Form.Submit style={{ width: '100%' }} type=\"primary\" validate onClick={this.handleSubmit}>Submit</Form.Submit>\n </FormItem>\n </Form>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
Response can be configured by Grid.Col
property of labelCol
wrapperCol
.
import { Form, Input, Select } from '@alifd/next';\n\n\nconst FormItem = Form.Item;\n\nconst formItemLayout = {\n labelCol: {xxs: 4, l: 4},\n wrapperCol: {xxs: 20, l: 16}\n};\n\nReactDOM.render(<Form {...formItemLayout} >\n <FormItem label=\"userName:\">\n <Input />\n </FormItem>\n <FormItem label=\"password:\">\n <Input htmlType=\"password\" name=\"resPass\" placeholder=\"Please Enter Password\"/>\n </FormItem>\n <FormItem label=\"Country:\">\n <Select placeholder=\"Please select a country\" style={{width: '100%'}}>\n <option value=\"china\">China</option>\n <option value=\"use\">United States</option>\n <option value=\"japan\">Japan</option>\n <option value=\"korean\">South Korea</option>\n <option value=\"Thailand\">Thailand</option>\n </Select>\n </FormItem>\n <FormItem label=\"Note:\" help=\"something\">\n <Input.TextArea placeholder=\"something\" name=\"resReremark\" />\n </FormItem>\n <FormItem label=\" \">\n <Form.Submit>Submit</Form.Submit>\n </FormItem>\n</Form>, mountNode);
可以通过配置 labelCol
wrapperCol
的 Grid.Col
响应式属性实现响应式
import { Form, Input, Select } from '@alifd/next';\n\n\nconst FormItem = Form.Item;\n\nconst formItemLayout = {\n labelCol: {xxs: 4, l: 4},\n wrapperCol: {xxs: 20, l: 16}\n};\n\nReactDOM.render(<Form {...formItemLayout} >\n <FormItem label=\"userName:\">\n <Input />\n </FormItem>\n <FormItem label=\"password:\">\n <Input htmlType=\"password\" name=\"resPass\" placeholder=\"Please Enter Password\"/>\n </FormItem>\n <FormItem label=\"Country:\">\n <Select placeholder=\"Please select a country\" style={{width: '100%'}}>\n <option value=\"china\">China</option>\n <option value=\"use\">United States</option>\n <option value=\"japan\">Japan</option>\n <option value=\"korean\">South Korea</option>\n <option value=\"Thailand\">Thailand</option>\n </Select>\n </FormItem>\n <FormItem label=\"Note:\" help=\"something\">\n <Input.TextArea placeholder=\"something\" name=\"resReremark\" />\n </FormItem>\n <FormItem label=\" \">\n <Form.Submit>Submit</Form.Submit>\n </FormItem>\n</Form>, mountNode);
labelAlign
Align of label
labelTextAlign
Align of text inlabel;
import { Form, Input, Select } from '@alifd/next';\n\n\nconst FormItem = Form.Item;\nconst Option = Select.Option;\nconst formItemLayout = {\n labelCol: {span: 4},\n wrapperCol: {span: 20}\n};\n\nclass Demo extends React.Component {\n state = {\n size: 'medium'\n }\n\n handleChange = (v) => {\n this.setState({\n size: v\n });\n }\n\n render() {\n return (\n <div>\n <Form {...formItemLayout} size={this.state.size} style={{maxWidth: '500px'}}>\n <FormItem label=\"Size:\">\n <Select value={this.state.size} onChange={this.handleChange} style={{width: '100%'}}>\n <Option value=\"small\">small</Option>\n <Option value=\"medium\">medium</Option>\n <Option value=\"large\">large</Option>\n </Select>\n </FormItem>\n <FormItem label=\"Account:\">\n <Input placeholder=\"Please enter your user name\" id=\"userName\" name=\"userName\"/>\n </FormItem>\n <FormItem required label=\"Password:\">\n <Input htmlType=\"password\" placeholder=\"Please enter your password\" id=\"password\" name=\"password\"/>\n </FormItem>\n <FormItem label=\"Password:\" validateState=\"error\">\n <Input htmlType=\"password\" placeholder=\"Check your password\" id=\"rePass\" name=\"rePass\"/>\n </FormItem>\n </Form>\n\n <br/><br/>\n\n <Form size={this.state.size} inline>\n <FormItem label=\"Size:\">\n <Select style={{width: '100%'}} value={this.state.size} onChange={this.handleChange}>\n <Option value=\"small\">small</Option>\n <Option value=\"medium\">medium</Option>\n <Option value=\"large\">large</Option>\n </Select>\n </FormItem>\n <FormItem label=\"Account:\">\n <Input placeholder=\"Please enter your user name\" id=\"userName2\" name=\"userName2\"/>\n </FormItem>\n <FormItem label=\"Password:\">\n <Input htmlType=\"password\" placeholder=\"Please enter your password\" id=\"password2\" name=\"password2\"/>\n </FormItem>\n <FormItem label=\"Password:\" validateState=\"error\">\n <Input htmlType=\"password\" placeholder=\"Check your password\" id=\"rePass2\" name=\"rePass2\"/>\n </FormItem>\n </Form>\n </div>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
.demo-ctl {\n background-color: #f1f1f1;\n padding: 10.0px;\n color: #0a7ac3;\n border-left: 4.0px solid #0d599a;\n}
size
会强制设置 FormItem
下的所有组件的size
labelAlign
label方位
labelTextAlign
文字左右对齐方式
import { Form, Input, Select } from '@alifd/next';\n\n\nconst FormItem = Form.Item;\nconst Option = Select.Option;\nconst formItemLayout = {\n labelCol: {span: 4},\n wrapperCol: {span: 20}\n};\n\nclass Demo extends React.Component {\n state = {\n size: 'medium'\n }\n\n handleChange = (v) => {\n this.setState({\n size: v\n });\n }\n\n render() {\n return (\n <div>\n <Form {...formItemLayout} size={this.state.size} style={{maxWidth: '500px'}}>\n <FormItem label=\"Size:\">\n <Select value={this.state.size} onChange={this.handleChange} style={{width: '100%'}}>\n <Option value=\"small\">small</Option>\n <Option value=\"medium\">medium</Option>\n <Option value=\"large\">large</Option>\n </Select>\n </FormItem>\n <FormItem label=\"Account:\">\n <Input placeholder=\"Please enter your user name\" id=\"userName\" name=\"userName\"/>\n </FormItem>\n <FormItem required label=\"Password:\">\n <Input htmlType=\"password\" placeholder=\"Please enter your password\" id=\"password\" name=\"password\"/>\n </FormItem>\n <FormItem label=\"Password:\" validateState=\"error\">\n <Input htmlType=\"password\" placeholder=\"Check your password\" id=\"rePass\" name=\"rePass\"/>\n </FormItem>\n </Form>\n\n <br/><br/>\n\n <Form size={this.state.size} inline>\n <FormItem label=\"Size:\">\n <Select style={{width: '100%'}} value={this.state.size} onChange={this.handleChange}>\n <Option value=\"small\">small</Option>\n <Option value=\"medium\">medium</Option>\n <Option value=\"large\">large</Option>\n </Select>\n </FormItem>\n <FormItem label=\"Account:\">\n <Input placeholder=\"Please enter your user name\" id=\"userName2\" name=\"userName2\"/>\n </FormItem>\n <FormItem label=\"Password:\">\n <Input htmlType=\"password\" placeholder=\"Please enter your password\" id=\"password2\" name=\"password2\"/>\n </FormItem>\n <FormItem label=\"Password:\" validateState=\"error\">\n <Input htmlType=\"password\" placeholder=\"Check your password\" id=\"rePass2\" name=\"rePass2\"/>\n </FormItem>\n </Form>\n </div>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
.demo-ctl {\n background-color: #f1f1f1;\n padding: 10.0px;\n color: #0a7ac3;\n border-left: 4.0px solid #0d599a;\n}
size
will specify the size of all components under FormItem
;
labelAlign
Align of label
labelTextAlign
Align of text inlabel;
import { Form, Input, Select } from '@alifd/next';\n\n\nconst FormItem = Form.Item;\nconst Option = Select.Option;\n\nclass Demo extends React.Component {\n render() {\n return (\n <div>\n <Form labelAlign=\"top\" >\n <FormItem label=\"Account:\">\n <Input placeholder=\"Please enter your user name\" id=\"userName\" name=\"userName\"/>\n </FormItem>\n\n <FormItem required label=\"Password:\">\n <Input htmlType=\"password\" placeholder=\"Please enter your password\" id=\"password\" name=\"password\"/>\n </FormItem>\n\n <FormItem label=\"Password:\" validateState=\"error\">\n <Input htmlType=\"password\" placeholder=\"Please enter your password\" id=\"rePass\" name=\"rePass\"/>\n </FormItem>\n\n <FormItem label=\"Size:\">\n <Select style={{width: '100%'}} name=\"size\">\n <Option value=\"small\">small</Option>\n <Option value=\"medium\">medium</Option>\n <Option value=\"large\">large</Option>\n </Select>\n </FormItem>\n </Form>\n\n <Form inline labelAlign=\"top\">\n <FormItem label=\"Account:\">\n <Input placeholder=\"Please enter your user name\" id=\"userName2\" name=\"userName2\"/>\n </FormItem>\n <FormItem label=\"Password:\">\n <Input htmlType=\"password\" placeholder=\"Please enter your password\" id=\"password2\" name=\"password2\"/>\n </FormItem>\n <FormItem label=\"Password:\" validateState=\"error\">\n <Input htmlType=\"password\" placeholder=\"Please enter your password\" id=\"rePass2\" name=\"rePass2\"/>\n </FormItem>\n <FormItem label=\"Size:\">\n <Select style={{width: '100%'}} name=\"size2\">\n <Option value=\"small\">small</Option>\n <Option value=\"medium\">medium</Option>\n <Option value=\"large\">large</Option>\n </Select>\n </FormItem>\n </Form>\n </div>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
.demo-ctl {\n background-color: #f1f1f1;\n padding: 10.0px;\n color: #0a7ac3;\n border-left: 4.0px solid #0d599a;\n}
size
会强制设置 FormItem
下的所有组件的size
labelAlign
label方位
labelTextAlign
文字左右对齐方式
import { Form, Input, Select } from '@alifd/next';\n\n\nconst FormItem = Form.Item;\nconst Option = Select.Option;\n\nclass Demo extends React.Component {\n render() {\n return (\n <div>\n <Form labelAlign=\"top\" >\n <FormItem label=\"Account:\">\n <Input placeholder=\"Please enter your user name\" id=\"userName\" name=\"userName\"/>\n </FormItem>\n\n <FormItem required label=\"Password:\">\n <Input htmlType=\"password\" placeholder=\"Please enter your password\" id=\"password\" name=\"password\"/>\n </FormItem>\n\n <FormItem label=\"Password:\" validateState=\"error\">\n <Input htmlType=\"password\" placeholder=\"Please enter your password\" id=\"rePass\" name=\"rePass\"/>\n </FormItem>\n\n <FormItem label=\"Size:\">\n <Select style={{width: '100%'}} name=\"size\">\n <Option value=\"small\">small</Option>\n <Option value=\"medium\">medium</Option>\n <Option value=\"large\">large</Option>\n </Select>\n </FormItem>\n </Form>\n\n <Form inline labelAlign=\"top\">\n <FormItem label=\"Account:\">\n <Input placeholder=\"Please enter your user name\" id=\"userName2\" name=\"userName2\"/>\n </FormItem>\n <FormItem label=\"Password:\">\n <Input htmlType=\"password\" placeholder=\"Please enter your password\" id=\"password2\" name=\"password2\"/>\n </FormItem>\n <FormItem label=\"Password:\" validateState=\"error\">\n <Input htmlType=\"password\" placeholder=\"Please enter your password\" id=\"rePass2\" name=\"rePass2\"/>\n </FormItem>\n <FormItem label=\"Size:\">\n <Select style={{width: '100%'}} name=\"size2\">\n <Option value=\"small\">small</Option>\n <Option value=\"medium\">medium</Option>\n <Option value=\"large\">large</Option>\n </Select>\n </FormItem>\n </Form>\n </div>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
.demo-ctl {\n background-color: #f1f1f1;\n padding: 10.0px;\n color: #0a7ac3;\n border-left: 4.0px solid #0d599a;\n}
Basic usage of validation.
\n","order":"9"},"codes":{"jsx":"import { Form, Input, Radio } from '@alifd/next';\n\n\nconst FormItem = Form.Item;\nconst RadioGroup = Radio.Group;\n\nconst formItemLayout = {\n labelCol: {\n span: 6\n },\n wrapperCol: {\n span: 14\n }\n};\n\nclass BasicDemo extends React.Component {\n userExists(rule, value) {\n return new Promise((resolve, reject) => {\n if (!value) {\n resolve();\n } else {\n setTimeout(() => {\n if (value === 'frank') {\n reject([new Error('Sorry, this username is already exist.')]);\n } else {\n resolve();\n }\n }, 500);\n }\n });\n }\n\n render() {\n return (\n \n );\n }\n}\n\nReactDOM.render(import { Form, Input, Radio } from '@alifd/next';\n\n\nconst FormItem = Form.Item;\nconst RadioGroup = Radio.Group;\n\nconst formItemLayout = {\n labelCol: {\n span: 6\n },\n wrapperCol: {\n span: 14\n }\n};\n\nclass BasicDemo extends React.Component {\n userExists(rule, value) {\n return new Promise((resolve, reject) => {\n if (!value) {\n resolve();\n } else {\n setTimeout(() => {\n if (value === 'frank') {\n reject([new Error('Sorry, this username is already exist.')]);\n } else {\n resolve();\n }\n }, 500);\n }\n });\n }\n\n render() {\n return (\n <Form {...formItemLayout} >\n <FormItem\n label=\"Account:\"\n hasFeedback\n validator={this.userExists.bind(this)}\n help=\"\"\n >\n <Input placeholder=\"Input frank\" name=\"valUsername\" />\n <Form.Error name=\"valUsername\" >{\n (errors, state) => {\n if (state === 'loading') {\n return 'loading...';\n } else {\n return errors;\n }\n }\n }</Form.Error>\n </FormItem>\n <FormItem\n label=\"Email:\"\n hasFeedback\n required\n requiredTrigger=\"onBlur\"\n format=\"email\"\n >\n <Input placeholder=\"Both trigget onBlur and onChange\" name=\"valEmail\" />\n </FormItem>\n\n <FormItem\n label=\"Password:\"\n hasFeedback\n required\n requiredMessage=\"Please enter password\"\n >\n <Input htmlType=\"password\" name=\"valPasswd\" />\n </FormItem>\n\n <FormItem\n label=\"Gender:\"\n hasFeedback\n required\n requiredMessage=\"Please select your gender\"\n >\n <RadioGroup name=\"valSex\" >\n <Radio value=\"male\">Male</Radio>\n <Radio value=\"female\">Female</Radio>\n </RadioGroup>\n </FormItem>\n\n <FormItem\n label=\"Remarks:\"\n required\n requiredMessage=\"Really do not intend to write anything?\"\n >\n <Input.TextArea maxLength={20} hasLimitHint placeholder=\"Everything is ok!\" name=\"valTextarea\" />\n </FormItem>\n\n <FormItem wrapperCol={{ offset: 6 }} >\n <Form.Submit validate type=\"primary\" onClick={(v, e) => console.log(v, e)} style={{marginRight: 10}}>Submit</Form.Submit>\n <Form.Reset >Reset</Form.Reset>\n </FormItem>\n </Form>\n );\n }\n}\n\nReactDOM.render(<BasicDemo />, mountNode);
基本的表单校验例子。
\n","order":"9"},"codes":{"jsx":"import { Form, Input, Radio } from '@alifd/next';\n\n\nconst FormItem = Form.Item;\nconst RadioGroup = Radio.Group;\n\nconst formItemLayout = {\n labelCol: {\n span: 6\n },\n wrapperCol: {\n span: 14\n }\n};\n\nclass BasicDemo extends React.Component {\n userExists(rule, value) {\n return new Promise((resolve, reject) => {\n if (!value) {\n resolve();\n } else {\n setTimeout(() => {\n if (value === 'frank') {\n reject([new Error('Sorry, this username is already exist.')]);\n } else {\n resolve();\n }\n }, 500);\n }\n });\n }\n\n render() {\n return (\n \n );\n }\n}\n\nReactDOM.render(import { Form, Input, Radio } from '@alifd/next';\n\n\nconst FormItem = Form.Item;\nconst RadioGroup = Radio.Group;\n\nconst formItemLayout = {\n labelCol: {\n span: 6\n },\n wrapperCol: {\n span: 14\n }\n};\n\nclass BasicDemo extends React.Component {\n userExists(rule, value) {\n return new Promise((resolve, reject) => {\n if (!value) {\n resolve();\n } else {\n setTimeout(() => {\n if (value === 'frank') {\n reject([new Error('Sorry, this username is already exist.')]);\n } else {\n resolve();\n }\n }, 500);\n }\n });\n }\n\n render() {\n return (\n <Form {...formItemLayout} >\n <FormItem\n label=\"Account:\"\n hasFeedback\n validator={this.userExists.bind(this)}\n help=\"\"\n >\n <Input placeholder=\"Input frank\" name=\"valUsername\" />\n <Form.Error name=\"valUsername\" >{\n (errors, state) => {\n if (state === 'loading') {\n return 'loading...';\n } else {\n return errors;\n }\n }\n }</Form.Error>\n </FormItem>\n <FormItem\n label=\"Email:\"\n hasFeedback\n required\n requiredTrigger=\"onBlur\"\n format=\"email\"\n >\n <Input placeholder=\"Both trigget onBlur and onChange\" name=\"valEmail\" />\n </FormItem>\n\n <FormItem\n label=\"Password:\"\n hasFeedback\n required\n requiredMessage=\"Please enter password\"\n >\n <Input htmlType=\"password\" name=\"valPasswd\" />\n </FormItem>\n\n <FormItem\n label=\"Gender:\"\n hasFeedback\n required\n requiredMessage=\"Please select your gender\"\n >\n <RadioGroup name=\"valSex\" >\n <Radio value=\"male\">Male</Radio>\n <Radio value=\"female\">Female</Radio>\n </RadioGroup>\n </FormItem>\n\n <FormItem\n label=\"Remarks:\"\n required\n requiredMessage=\"Really do not intend to write anything?\"\n >\n <Input.TextArea maxLength={20} hasLimitHint placeholder=\"Everything is ok!\" name=\"valTextarea\" />\n </FormItem>\n\n <FormItem wrapperCol={{ offset: 6 }} >\n <Form.Submit validate type=\"primary\" onClick={(v, e) => console.log(v, e)} style={{marginRight: 10}}>Submit</Form.Submit>\n <Form.Reset >Reset</Form.Reset>\n </FormItem>\n </Form>\n );\n }\n}\n\nReactDOM.render(<BasicDemo />, mountNode);
Basic usage of validation.
\n","order":"9"},"codes":{"jsx":"import { Form, Input, Field } from '@alifd/next';\n\n\nconst FormItem = Form.Item;\n\nconst formItemLayout = {\n labelCol: {\n span: 6\n },\n wrapperCol: {\n span: 14\n }\n};\n\nclass BasicDemo extends React.Component {\n field = new Field(this);\n\n render() {\n const {\n field,\n field: {\n init,\n }\n } = this;\n return (\nimport { Form, Input, Field } from '@alifd/next';\n\n\nconst FormItem = Form.Item;\n\nconst formItemLayout = {\n labelCol: {\n span: 6\n },\n wrapperCol: {\n span: 14\n }\n};\n\nclass BasicDemo extends React.Component {\n field = new Field(this);\n\n render() {\n const {\n field,\n field: {\n init,\n }\n } = this;\n return (\n <Form {...formItemLayout} field={field} >\n\n <Form.Item label=\"test\" key=\"test2\">\n <Input {...init('input', {\n rules: [{\n validator(_rule, value, callback) {\n callback(<span>This is a <em>CUSTOM</em> error</span>);\n }\n }]\n })} />\n </Form.Item>\n <FormItem wrapperCol={{ offset: 6 }} >\n <Form.Submit validate type=\"primary\">Submit</Form.Submit>\n <Form.Reset >Reset</Form.Reset>\n </FormItem>\n </Form>\n );\n }\n}\n\nReactDOM.render(<BasicDemo />, mountNode);
基本的表单校验例子。
\n","order":"9"},"codes":{"jsx":"import { Form, Input, Field } from '@alifd/next';\n\n\nconst FormItem = Form.Item;\n\nconst formItemLayout = {\n labelCol: {\n span: 6\n },\n wrapperCol: {\n span: 14\n }\n};\n\nclass BasicDemo extends React.Component {\n field = new Field(this);\n\n render() {\n const {\n field,\n field: {\n init,\n }\n } = this;\n return (\nimport { Form, Input, Field } from '@alifd/next';\n\n\nconst FormItem = Form.Item;\n\nconst formItemLayout = {\n labelCol: {\n span: 6\n },\n wrapperCol: {\n span: 14\n }\n};\n\nclass BasicDemo extends React.Component {\n field = new Field(this);\n\n render() {\n const {\n field,\n field: {\n init,\n }\n } = this;\n return (\n <Form {...formItemLayout} field={field} >\n\n <Form.Item label=\"test\" key=\"test2\">\n <Input {...init('input', {\n rules: [{\n validator(_rule, value, callback) {\n callback(<span>This is a <em>CUSTOM</em> error</span>);\n }\n }]\n })} />\n </Form.Item>\n <FormItem wrapperCol={{ offset: 6 }} >\n <Form.Submit validate type=\"primary\">Submit</Form.Submit>\n <Form.Reset >Reset</Form.Reset>\n </FormItem>\n </Form>\n );\n }\n}\n\nReactDOM.render(<BasicDemo />, mountNode);
Define the state
attribute for <FormItem>
to control the three valedation states.
If it is an <Input>
component, you can add hasFeedback
to control icon on <FormItem>
Note: The feedback icon is only valid for <Input />
.
import { Form, Input, DatePicker, TimePicker, NumberPicker, Select } from '@alifd/next';\n\n\nconst FormItem = Form.Item;\n\nconst formItemLayout = {\n labelCol: {\n span: 6\n },\n wrapperCol: {\n span: 14\n }\n};\n\nReactDOM.render(\n <Form {...formItemLayout}>\n <FormItem label=\"Input Error:\" validateState=\"error\" help=\"Please enter a numeric and alphabetic string\">\n <Input defaultValue=\"Invalid choice\"/>\n </FormItem>\n\n <FormItem label=\"Loading:\" hasFeedback validateState=\"loading\" help=\"Information Checking...\">\n <Input defaultValue=\"Checking\"/>\n </FormItem>\n\n <FormItem label=\"Success:\" hasFeedback validateState=\"success\">\n <Input defaultValue=\"Successful verification\"/>\n </FormItem>\n\n <FormItem label=\"Datepicker:\" validateState=\"error\" help=\"Please select the correct date\">\n <DatePicker />\n </FormItem>\n\n <FormItem label=\"Timepicker:\" validateState=\"error\" help=\"Please select the correct time\">\n <TimePicker />\n </FormItem>\n\n <FormItem label=\"Select:\" validateState=\"error\" help=\"Please select a country\">\n <Select placeholder=\"Please select a country\">\n <option value=\"china\">China</option>\n <option value=\"use\">United States</option>\n <option value=\"japan\">Japan</option>\n <option value=\"korean\">South Korea</option>\n <option value=\"Thailand\">Thailand</option>\n </Select>\n </FormItem>\n\n <FormItem label=\"NumberPicker:\" validateState=\"error\">\n <NumberPicker defaultValue={0} />\n </FormItem>\n </Form>\n , mountNode);
为 <FormItem>
定义 state
属性控制三种校验状态。
如果是 <Input>
组件, 可在<FormItem>
上面添加 hasFeedback
控制图标的展示
注意: 反馈图标只对 <Input />
有效。
import { Form, Input, DatePicker, TimePicker, NumberPicker, Select } from '@alifd/next';\n\n\nconst FormItem = Form.Item;\n\nconst formItemLayout = {\n labelCol: {\n span: 6\n },\n wrapperCol: {\n span: 14\n }\n};\n\nReactDOM.render(\n <Form {...formItemLayout}>\n <FormItem label=\"Input Error:\" validateState=\"error\" help=\"Please enter a numeric and alphabetic string\">\n <Input defaultValue=\"Invalid choice\"/>\n </FormItem>\n\n <FormItem label=\"Loading:\" hasFeedback validateState=\"loading\" help=\"Information Checking...\">\n <Input defaultValue=\"Checking\"/>\n </FormItem>\n\n <FormItem label=\"Success:\" hasFeedback validateState=\"success\">\n <Input defaultValue=\"Successful verification\"/>\n </FormItem>\n\n <FormItem label=\"Datepicker:\" validateState=\"error\" help=\"Please select the correct date\">\n <DatePicker />\n </FormItem>\n\n <FormItem label=\"Timepicker:\" validateState=\"error\" help=\"Please select the correct time\">\n <TimePicker />\n </FormItem>\n\n <FormItem label=\"Select:\" validateState=\"error\" help=\"Please select a country\">\n <Select placeholder=\"Please select a country\">\n <option value=\"china\">China</option>\n <option value=\"use\">United States</option>\n <option value=\"japan\">Japan</option>\n <option value=\"korean\">South Korea</option>\n <option value=\"Thailand\">Thailand</option>\n </Select>\n </FormItem>\n\n <FormItem label=\"NumberPicker:\" validateState=\"error\">\n <NumberPicker defaultValue={0} />\n </FormItem>\n </Form>\n , mountNode);
Form layout, validation, data submission operations used.
\nnodeName
as the name and input`s id.size="medium"
by default and controls the size of all components in the FormItem. If you want to modify the component size, set <FormItem size="small" >
.<p>
tag) or component deviates upwards, it can be adjusted with className="next-form-text-align"
<FormItem>
to display the error message. If the error did not show, check whether there are multiple levels DOM. For example, <FormItem><div><Input/></div></FormItem>
is unable to display error message.<Form field={false}>
to close inner fieldParam | \nDescripiton | \nType | \nDefault Value | \n
---|---|---|---|
inline | \nInline form | \nBoolean | \n- | \n
size | \nCustomization of a single Item's size takes precedence over Form's size, and when the component is used with Item, the component itself sets the size attribute to be invalid. option: 'large' 'medium' 'small' | \nEnum | \n'medium' | \n
fullWidth | \nSet a single Item's is full width | \nBoolean | \n- | \n
labelAlign | \nTo set the position align of label option: 'top' 'left' 'inset' | \nEnum | \n'left' | \n
labelTextAlign | \nTo set the position align of text in label option: 'left' 'right' | \nEnum | \n- | \n
field | \nBy the initialization of new Field(this) , set to Form right. Do not ignore specify this, when use validation on form. | \nany | \n- | \n
saveField | \nsave field which create by Form 签名: Function() => void | \nFunction | \nfunc.noop | \n
labelCol | \nControls the labelCol of the first-level Item | \nObject | \n- | \n
wrapperCol | \nControls the wrapperCol of the first-level Item | \nObject | \n- | \n
onSubmit | \nTrigget when submit with htmlType="submit" in the form signatures: Function() => void | \nFunction | \nfunction preventDefault(e) { e.preventDefault(); } | \n
children | \nChildren components | \nany | \n- | \n
value | \nThe value data of then form | \nObject | \n- | \n
onChange | \nCallback fuction trigget on form changed signatures: Function() => void | \nFunction | \nfunc.noop | \n
component | \nThe html tag to be rendered | \nString | \n'form' | \n
\n\nPassing the wrapCol labelCol will use the Grid auxiliary layout;
\nlabelAlign = 'top'
will force the Grid to be disabled
Param | \nDescripiton | \nType | \nDefault Value | \n
---|---|---|---|
label | \nTo set the label of item | \nReactNode | \n- | \n
size | \nCustomization of Item's own size takes precedence over Form's size. when Form and Item both set the size, the component itself sets the size attribute to be invalid。 option: 'large', 'small', 'medium' | \nEnum | \n- | \n
fullWidth | \nSet Input item is full width | \nBoolean | \n- | \n
labelCol | \nTo set label's layout same as <Col> setting the span offset, such as {span:8,offset:16}. It only valid in vertical forms. | \nObject | \n- | \n
wrapperCol | \nWhen you need to set the layout style for the input control, use this property, use the same with the labelCol | \nObject | \n- | \n
help | \nCustom prompt information, if not set, it will be automatically generated according to the check rule. | \nReactNode | \n- | \n
validateState | \nSet the validation state, if not set, it will be automatically generated according to the check rule option: 'error' 'success' 'loading' | \nEnum | \n- | \n
hasFeedback | \nUsed with the validateState property, whether to display the success/loading check status icon. Currently only Input support | \nBoolean | \nfalse | \n
extra | \nAdditional prompt information, similar to help, can be used when error messages and prompts are required to appear at the same time. Behind the error message | \nReactNode | \n- | \n
labelAlign | \nPosition align of label option: 'top' 'left' 'inset' | \nEnum | \n- | \n
labelTextAlign | \nPosition align of label's text option: 'left' 'right' | \nEnum | \n- | \n
required | \n[validation] cannot be empty | \nBoolean | \n- | \n
asterisk | \nrequired asterisk is displayed | \nBoolean | \ntrue | \n
requiredMessage | \nrequired custom error message | \nString | \n- | \n
requiredTrigger | \nrequired Custom Trigger | \nString/Array | \n- | \n
min | \n[validation] Minimum | \nNumber | \n- | \n
minMessage | \ncustom error message for min | \nString | \n- | \n
minTrigger | \nCustom trigger mode for min | \nString/Array | \n- | \n
max | \n[validation] Maximum | \nNumber | \n- | \n
maxMessage | \ncustom error message for max | \nString | \n- | \n
maxTrigger | \nCustom Trigger for max | \nString/Array | \n- | \n
minLength | \n[validation] Minimum string length / Minimum number of arrays | \nNumber | \n- | \n
minLengthMessage | \ncustom error message for minLength | \nString | \n- | \n
minLengthTrigger | \nCustom Trigger for minLength | \nString/Array | \n- | \n
maxLength | \n[validation] Max Length of String/Maximum Number of Arrays | \nNumber | \n- | \n
maxLengthMessage | \ncustom error message for maxLength | \nString | \n- | \n
maxLengthTrigger | \nCustom Trigger for maxLength | \nString/Array | \n- | \n
length | \n[validation] exact length of string / exact number of arrays | \nNumber | \n- | \n
lengthMessage | \ncustom error message for length | \nString | \n- | \n
lengthTrigger | \ncustom trigger method for length | \nString/Array | \n- | \n
pattern | \ncustom pattern yourself | \npattern | \n- | \n
format | \n[validation] four common patterns optional values: 'number', 'email', 'url', 'tel' | \nEnum | \n- | \n
formatMessage | \ncustom error message for format | \nString | \n- | \n
formatTrigger | \ncustom trigger mode for format | \nString/Array | \n- | \n
validator | \n[validation] custom validation function signature : Function() => void | \nFunction | \n- | \n
autoValidate | \nvalidate while value changed | \nBoolean | \n- | \n
\n\nInherit the Button API
\n
Param | \nDescripiton | \nType | \nDefault Value | \n
---|---|---|---|
names | \nSpecify the reset field | \nArray | \n- | \n
onClick | \nCallback function trigget after click Reset-Button signatures: Function() => void | \nFunction | \nfunc.noop | \n
toDefault | \nReset to default value | \nBoolean | \n- | \n
field | \nSpecify field (No need in Form ) | \nObject | \n- | \n
\n\nInherit the Button API
\n
Param | \nDescripiton | \nType | \nDefault Value | \n
---|---|---|---|
onClick | \nCallback function trigget after click Submit-Button signatures: Function(value: Object, errors: Object) => void params: value: {Object} values errors: {Object} errors field: {class} Field instance | \nFunction | \nfunc.noop | \n
validate | \nSpecify the field, whitch need validate. | \nBoolean/Array | \n- | \n
field | \nSpecify field (No need in Form ) | \nObject | \n- | \n
\n\ncustom error message
\n
Param | \nDescripiton | \nType | \nDefault Value | \n
---|---|---|---|
name | \nSpecify the reset field | \nString/Array | \n- | \n
field | \nSpecify field (No need in Form ) | \nObject | \n- | \n
children | \ncan be a ReactNode or a function(errors, state) | \nReactNode/Function | \n- | \n
Field
component documentation.If your form scene is very complex, such as dynamic rendering, a large number of fields, complex data structures, complex linkage verification, you can consider using uform, uform has encapsulated all the fusion components, to ensure that you use it out of the box
\n"} \ No newline at end of file diff --git a/compiled_docs/form/index.md b/compiled_docs/form/index.md new file mode 100644 index 0000000000..f34b3bdc13 --- /dev/null +++ b/compiled_docs/form/index.md @@ -0,0 +1 @@ +{"meta":"表单布局、校验、数据提交操作时用到。 组件的设计思想可以看这篇文章 https://zhuanlan.zhihu.com/p/56280821
\nnodeName
作为 name、idsize=medium
, 并且会控制 FormItem 内所有组件的size。 如果想修改组件的size <FormItem size="small" >
<p>
标签)或者组件向上偏离,可以通过 className="next-form-text-align"
辅助调整<FormItem>
直接包裹的组件才能展示校验错误提示。如果界面不展示错误信息,请检查是否有多个层级。 比如 <FormItem><div><Input/></div></FormItem>
是无法展示校验信息的。<Form field={false}>
来关闭数据获取,变成一个纯布局组件参数 | \n说明 | \n类型 | \n默认值 | \n
---|---|---|---|
inline | \n内联表单 | \nBoolean | \n- | \n
size | \n单个 Item 的 size 自定义,优先级高于 Form 的 size, 并且当组件与 Item 一起使用时,组件自身设置 size 属性无效。 可选值: 'large'(大) 'medium'(中) 'small'(小) | \nEnum | \n'medium' | \n
fullWidth | \n单个 Item 中表单类组件宽度是否是100% | \nBoolean | \n- | \n
labelAlign | \n标签的位置 可选值: 'top'(上) 'left'(左) 'inset'(内) | \nEnum | \n'left' | \n
labelTextAlign | \n标签的左右对齐方式 可选值: 'left'(左) 'right'(右) | \nEnum | \n- | \n
field | \nfield 实例, 传 false 会禁用 field | \nany | \n- | \n
saveField | \n保存 Form 自动生成的 field 对象 签名: Function() => void | \nFunction | \nfunc.noop | \n
labelCol | \n控制第一级 Item 的 labelCol | \nObject | \n- | \n
wrapperCol | \n控制第一级 Item 的 wrapperCol | \nObject | \n- | \n
onSubmit | \nform内有 htmlType="submit" 的元素的时候会触发签名: Function() => void | \nFunction | \nfunction preventDefault(e) { e.preventDefault(); } | \n
children | \n子元素 | \nany | \n- | \n
value | \n表单数值 | \nObject | \n- | \n
onChange | \n表单变化回调 签名: Function(values: Object, item: Object) => void 参数: values: {Object} 表单数据 item: {Object} 详细 item.name: {String} 变化的组件名 item.value: {String} 变化的数据 item.field: {Object} field 实例 | \nFunction | \nfunc.noop | \n
component | \n设置标签类型 | \nString/Function | \n'form' | \n
device | \n预设屏幕宽度 可选值: 'phone', 'tablet', 'desktop' | \nEnum | \n'desktop' | \n
\n\n手动传递了 wrapCol labelCol 会使用 Grid 辅助布局; labelAlign='top' 会强制禁用 Grid
\n
参数 | \n说明 | \n类型 | \n默认值 | \n
---|---|---|---|
label | \nlabel 标签的文本 | \nReactNode | \n- | \n
size | \n单个 Item 的 size 自定义,优先级高于 Form 的 size, 并且当组件与 Item 一起使用时,组件自身设置 size 属性无效。 可选值: 'large', 'small', 'medium' | \nEnum | \n- | \n
labelCol | \nlabel 标签布局,通 <Col> 组件,设置 span offset 值,如 {span: 8, offset: 16},该项仅在垂直表单有效 | \nObject | \n- | \n
wrapperCol | \n需要为输入控件设置布局样式时,使用该属性,用法同 labelCol | \nObject | \n- | \n
help | \n自定义提示信息,如不设置,则会根据校验规则自动生成. | \nReactNode | \n- | \n
extra | \n额外的提示信息,和 help 类似,当需要错误信息和提示文案同时出现时,可以使用这个。 位于错误信息后面 | \nReactNode | \n- | \n
validateState | \n校验状态,如不设置,则会根据校验规则自动生成 可选值: 'error'(失败) 'success'(成功) 'loading'(校验中) | \nEnum | \n- | \n
hasFeedback | \n配合 validateState 属性使用,是否展示 success/loading 的校验状态图标, 目前只有Input支持 | \nBoolean | \nfalse | \n
children | \nnode 或者 function(values) | \nReactNode/Function | \n- | \n
fullWidth | \n单个 Item 中表单类组件宽度是否是100% | \nBoolean | \n- | \n
labelAlign | \n标签的位置 可选值: 'top'(上) 'left'(左) 'inset'(内) | \nEnum | \n- | \n
labelTextAlign | \n标签的左右对齐方式 可选值: 'left'(左) 'right'(右) | \nEnum | \n- | \n
required | \n[表单校验] 不能为空 | \nBoolean | \n- | \n
asterisk | \nrequired 的星号是否显示 | \nBoolean | \n- | \n
requiredMessage | \nrequired 自定义错误信息 | \nString | \n- | \n
requiredTrigger | \nrequired 自定义触发方式 | \nString/Array | \n- | \n
min | \n[表单校验] 最小值 | \nNumber | \n- | \n
max | \n[表单校验] 最大值 | \nNumber | \n- | \n
minmaxMessage | \nmin/max 自定义错误信息 | \nString | \n- | \n
minmaxTrigger | \nmin/max 自定义触发方式 | \nString/Array | \n- | \n
minLength | \n[表单校验] 字符串最小长度 / 数组最小个数 | \nNumber | \n- | \n
maxLength | \n[表单校验] 字符串最大长度 / 数组最大个数 | \nNumber | \n- | \n
minmaxLengthMessage | \nminLength/maxLength 自定义错误信息 | \nString | \n- | \n
minmaxLengthTrigger | \nminLength/maxLength 自定义触发方式 | \nString/Array | \n- | \n
length | \n[表单校验] 字符串精确长度 / 数组精确个数 | \nNumber | \n- | \n
lengthMessage | \nlength 自定义错误信息 | \nString | \n- | \n
lengthTrigger | \nlength 自定义触发方式 | \nString/Array | \n- | \n
pattern | \n正则校验 | \nany | \n- | \n
patternMessage | \npattern 自定义错误信息 | \nString | \n- | \n
patternTrigger | \npattern 自定义触发方式 | \nString/Array | \n- | \n
format | \n[表单校验] 四种常用的 pattern 可选值: 'number', 'email', 'url', 'tel' | \nEnum | \n- | \n
formatMessage | \nformat 自定义错误信息 | \nString | \n- | \n
formatTrigger | \nformat 自定义触发方式 | \nString/Array | \n- | \n
validator | \n[表单校验] 自定义校验函数 签名: Function() => void | \nFunction | \n- | \n
validatorTrigger | \nvalidator 自定义触发方式 | \nString/Array | \n- | \n
autoValidate | \n是否修改数据时自动触发校验 | \nBoolean | \n- | \n
device | \n预设屏幕宽度 可选值: 'phone', 'tablet', 'desktop' | \nEnum | \n- | \n
\n\n继承 Button API
\n
参数 | \n说明 | \n类型 | \n默认值 | \n
---|---|---|---|
onClick | \n点击提交后触发 签名: Function(value: Object, errors: Object, field: class) => void 参数: value: {Object} 数据 errors: {Object} 错误数据 field: {class} 实例 | \nFunction | \nfunc.noop | \n
validate | \n是否校验/需要校验的 name 数组 | \nBoolean/Array | \n- | \n
field | \n自定义 field (在 Form 内不需要设置) | \nObject | \n- | \n
\n\n继承 Button API
\n
参数 | \n说明 | \n类型 | \n默认值 | \n
---|---|---|---|
names | \n自定义重置的字段 | \nArray | \n- | \n
onClick | \n点击提交后触发 签名: Function() => void | \nFunction | \nfunc.noop | \n
toDefault | \n返回默认值 | \nBoolean | \n- | \n
field | \n自定义 field (在 Form 内不需要设置) | \nObject | \n- | \n
\n\n自定义错误展示
\n
参数 | \n说明 | \n类型 | \n默认值 | \n
---|---|---|---|
name | \n表单名 | \nString/Array | \n- | \n
field | \n自定义 field (在 Form 内不需要设置) | \nObject | \n- | \n
children | \n自定义错误渲染, 可以是 node 或者 function(errors, state) | \nReactNode/Function | \n- | \n
Field
组件文档的 rules如果您的表单场景非常复杂,比如动态渲染,大量字段,复杂数据结构,复杂联动校验,可以考虑使用 uform,uform已经封装了所有fusion组件,保证您开箱即用
\n"} \ No newline at end of file diff --git a/compiled_docs/grid/demo/align.en-us.md b/compiled_docs/grid/demo/align.en-us.md new file mode 100644 index 0000000000..6b1371b32e --- /dev/null +++ b/compiled_docs/grid/demo/align.en-us.md @@ -0,0 +1 @@ +{"title":"Vertical alignment of columns","meta":{"title":"Vertical alignment of columns","description":"\n(IE9 is not supported) Based on Flex's align-items and align-self attributes, set the align
property on Row
to control the vertical alignment of all Col
below Row
: top (top alignment, default), center (center alignment), bottom (bottom alignment), baseline (baseline alignment of the first line of text), stretch (if no height is set or set to auto, it will fill the height of the entire container); set the align
property on Col
, it can override the align
property of Row
.
import { Grid } from '@alifd/next';\n\nconst { Row, Col } = Grid;\n\nReactDOM.render(\n <div className=\"align-demo\">\n <div className=\"demo-title\">top</div>\n <Row align=\"top\">\n <Col span=\"8\" style={{ height: '100px', lineHeight: '100px' }}>col-8</Col>\n <Col span=\"8\" style={{ height: '50px', lineHeight: '50px' }}>col-8</Col>\n <Col span=\"8\" style={{ height: '150px', lineHeight: '150px' }}>col-8</Col>\n </Row>\n\n <div className=\"demo-title\">center</div>\n <Row align=\"center\">\n <Col span=\"8\" style={{ height: '100px', lineHeight: '100px' }}>col-8</Col>\n <Col span=\"8\" style={{ height: '50px', lineHeight: '50px' }}>col-8</Col>\n <Col span=\"8\" style={{ height: '150px', lineHeight: '150px' }}>col-8</Col>\n </Row>\n\n <div className=\"demo-title\">bottom</div>\n <Row align=\"bottom\">\n <Col span=\"8\" style={{ height: '100px', lineHeight: '100px' }}>col-8</Col>\n <Col span=\"8\" style={{ height: '50px', lineHeight: '50px' }}>col-8</Col>\n <Col span=\"8\" style={{ height: '150px', lineHeight: '150px' }}>col-8</Col>\n </Row>\n\n <div className=\"demo-title\">baseline</div>\n <Row align=\"baseline\">\n <Col span=\"8\" style={{ height: '100px', paddingTop: '20px', fontSize: '30px' }}>col-8</Col>\n <Col span=\"8\" style={{ height: '50px', paddingTop: '20px', fontSize: '20px' }}>col-8</Col>\n <Col span=\"8\" style={{ height: '150px', paddingTop: '20px', fontSize: '40px' }}>col-8</Col>\n </Row>\n\n <div className=\"demo-title\">stretch</div>\n <Row align=\"stretch\" style={{ height: '150px' }}>\n <Col span=\"8\">col-8</Col>\n <Col span=\"8\">col-8</Col>\n <Col span=\"8\">col-8</Col>\n </Row>\n\n <div className=\"demo-title\">override</div>\n <Row align=\"top\">\n <Col align=\"bottom\" span=\"8\" style={{ height: '100px', lineHeight: '100px' }}>col-8</Col>\n <Col span=\"8\" style={{ height: '50px', lineHeight: '50px' }}>col-8</Col>\n <Col span=\"8\" style={{ height: '150px', lineHeight: '150px' }}>col-8</Col>\n </Row>\n </div>, mountNode);
.align-demo .demo-title {\n margin-left: 20px;\n}\n\n.align-demo .next-row {\n margin: 10px 0;\n}\n\n.align-demo .next-col {\n border:1px solid #CCC;\n border-radius: 3px;\n background-color:#ECECEC;\n line-height: 30px;\n text-align: center;\n}
(不支持 IE9 浏览器)基于 Flex 的 align-items 和 align-self 属性实现,在 Row
上设置 align
属性,即可控制 Row
下面所有 Col
的垂直方向对齐方式:top(顶部对齐,默认),center(居中对齐),bottom(底部对齐),baseline(第一行文字的基线对齐),stretch(如果未设置高度或设为 auto,将占满整个容器的高度);在 Col
上设置 align
属性,可允许它与其它列不一样的对齐方式,覆盖 Row
的 align
属性。
import { Grid } from '@alifd/next';\n\nconst { Row, Col } = Grid;\n\nReactDOM.render(\n <div className=\"align-demo\">\n <div className=\"demo-title\">top</div>\n <Row align=\"top\">\n <Col span=\"8\" style={{ height: '100px', lineHeight: '100px' }}>col-8</Col>\n <Col span=\"8\" style={{ height: '50px', lineHeight: '50px' }}>col-8</Col>\n <Col span=\"8\" style={{ height: '150px', lineHeight: '150px' }}>col-8</Col>\n </Row>\n\n <div className=\"demo-title\">center</div>\n <Row align=\"center\">\n <Col span=\"8\" style={{ height: '100px', lineHeight: '100px' }}>col-8</Col>\n <Col span=\"8\" style={{ height: '50px', lineHeight: '50px' }}>col-8</Col>\n <Col span=\"8\" style={{ height: '150px', lineHeight: '150px' }}>col-8</Col>\n </Row>\n\n <div className=\"demo-title\">bottom</div>\n <Row align=\"bottom\">\n <Col span=\"8\" style={{ height: '100px', lineHeight: '100px' }}>col-8</Col>\n <Col span=\"8\" style={{ height: '50px', lineHeight: '50px' }}>col-8</Col>\n <Col span=\"8\" style={{ height: '150px', lineHeight: '150px' }}>col-8</Col>\n </Row>\n\n <div className=\"demo-title\">baseline</div>\n <Row align=\"baseline\">\n <Col span=\"8\" style={{ height: '100px', paddingTop: '20px', fontSize: '30px' }}>col-8</Col>\n <Col span=\"8\" style={{ height: '50px', paddingTop: '20px', fontSize: '20px' }}>col-8</Col>\n <Col span=\"8\" style={{ height: '150px', paddingTop: '20px', fontSize: '40px' }}>col-8</Col>\n </Row>\n\n <div className=\"demo-title\">stretch</div>\n <Row align=\"stretch\" style={{ height: '150px' }}>\n <Col span=\"8\">col-8</Col>\n <Col span=\"8\">col-8</Col>\n <Col span=\"8\">col-8</Col>\n </Row>\n\n <div className=\"demo-title\">override</div>\n <Row align=\"top\">\n <Col align=\"bottom\" span=\"8\" style={{ height: '100px', lineHeight: '100px' }}>col-8</Col>\n <Col span=\"8\" style={{ height: '50px', lineHeight: '50px' }}>col-8</Col>\n <Col span=\"8\" style={{ height: '150px', lineHeight: '150px' }}>col-8</Col>\n </Row>\n </div>, mountNode);
.align-demo .demo-title {\n margin-left: 20px;\n}\n\n.align-demo .next-row {\n margin: 10px 0;\n}\n\n.align-demo .next-col {\n border:1px solid #CCC;\n border-radius: 3px;\n background-color:#ECECEC;\n line-height: 30px;\n text-align: center;\n}
Use the span
property of Col
to specify the width of the column.
import { Grid } from '@alifd/next';\n\nconst { Row, Col } = Grid;\n\nReactDOM.render(\n <div className=\"basic-demo\">\n <div className=\"demo-title\">One</div>\n <Row>\n <Col span=\"24\">col-24</Col>\n </Row>\n\n <div className=\"demo-title\">Two</div>\n <Row>\n <Col span=\"12\">col-12</Col>\n <Col span=\"12\">col-12</Col>\n </Row>\n\n <div className=\"demo-title\">Three</div>\n <Row>\n <Col span=\"8\">col-8</Col>\n <Col span=\"8\">col-8</Col>\n <Col span=\"8\">col-8</Col>\n </Row>\n\n <div className=\"demo-title\">Four</div>\n <Row>\n <Col span=\"6\">col-6</Col>\n <Col span=\"6\">col-6</Col>\n <Col span=\"6\">col-6</Col>\n <Col span=\"6\">col-6</Col>\n </Row>\n\n <div className=\"demo-title\">Five</div>\n <Row>\n <Col span=\"1p5\">col-1p5</Col>\n <Col span=\"1p5\">col-1p5</Col>\n <Col span=\"1p5\">col-1p5</Col>\n <Col span=\"1p5\">col-1p5</Col>\n <Col span=\"1p5\">col-1p5</Col>\n </Row>\n\n <div className=\"demo-title\">Six</div>\n <Row>\n <Col span=\"4\">col-4</Col>\n <Col span=\"4\">col-4</Col>\n <Col span=\"4\">col-4</Col>\n <Col span=\"4\">col-4</Col>\n <Col span=\"4\">col-4</Col>\n <Col span=\"4\">col-4</Col>\n </Row>\n </div>, mountNode);
.basic-demo .demo-title {\n margin-left: 20px;\n}\n\n.basic-demo .next-row {\n margin: 10px 0;\n}\n\n.basic-demo .next-col {\n border:1px solid #CCC;\n border-radius: 3px;\n background-color:#ECECEC;\n height: 30px;\n line-height: 30px;\n text-align: center;\n}
通过 Col
的 span
属性指定该列宽度占整行宽度24分之几或5分之几。
import { Grid } from '@alifd/next';\n\nconst { Row, Col } = Grid;\n\nReactDOM.render(\n <div className=\"basic-demo\">\n <div className=\"demo-title\">One</div>\n <Row>\n <Col span=\"24\">col-24</Col>\n </Row>\n\n <div className=\"demo-title\">Two</div>\n <Row>\n <Col span=\"12\">col-12</Col>\n <Col span=\"12\">col-12</Col>\n </Row>\n\n <div className=\"demo-title\">Three</div>\n <Row>\n <Col span=\"8\">col-8</Col>\n <Col span=\"8\">col-8</Col>\n <Col span=\"8\">col-8</Col>\n </Row>\n\n <div className=\"demo-title\">Four</div>\n <Row>\n <Col span=\"6\">col-6</Col>\n <Col span=\"6\">col-6</Col>\n <Col span=\"6\">col-6</Col>\n <Col span=\"6\">col-6</Col>\n </Row>\n\n <div className=\"demo-title\">Five</div>\n <Row>\n <Col span=\"1p5\">col-1p5</Col>\n <Col span=\"1p5\">col-1p5</Col>\n <Col span=\"1p5\">col-1p5</Col>\n <Col span=\"1p5\">col-1p5</Col>\n <Col span=\"1p5\">col-1p5</Col>\n </Row>\n\n <div className=\"demo-title\">Six</div>\n <Row>\n <Col span=\"4\">col-4</Col>\n <Col span=\"4\">col-4</Col>\n <Col span=\"4\">col-4</Col>\n <Col span=\"4\">col-4</Col>\n <Col span=\"4\">col-4</Col>\n <Col span=\"4\">col-4</Col>\n </Row>\n </div>, mountNode);
.basic-demo .demo-title {\n margin-left: 20px;\n}\n\n.basic-demo .next-row {\n margin: 10px 0;\n}\n\n.basic-demo .next-col {\n border:1px solid #CCC;\n border-radius: 3px;\n background-color:#ECECEC;\n height: 30px;\n line-height: 30px;\n text-align: center;\n}
Similar to Bootstrap's responsive design, it presets six response sizes: xxs (320px), xs (480px), s (720px), m (990px), l (1200px), and xl (1500px).
\n","order":"5"},"codes":{"jsx":"import { Grid } from '@alifd/next';\n\nconst { Row, Col } = Grid;\n\nReactDOM.render(\nimport { Grid } from '@alifd/next';\n\nconst { Row, Col } = Grid;\n\nReactDOM.render(\n <div className=\"breakpoint-demo\">\n <div className=\"demo-title\">Resize browser to see how each column changes</div>\n <Row >\n <Col xs={12} s={8} m={6}>Col</Col>\n <Col xs={6} s={8} m={6}>Col</Col>\n <Col xs={6} s={8} m={12}>Col</Col>\n </Row>\n </div>, mountNode);
.breakpoint-demo .demo-title {\n margin-left: 20px;\n}\n\n.breakpoint-demo .next-row {\n margin: 10px 0;\n}\n\n.breakpoint-demo .next-col {\n border:1px solid #CCC;\n border-radius: 3px;\n background-color:#ECECEC;\n height: 30px;\n line-height: 30px;\n text-align: center;\n}
import { Grid } from '@alifd/next';\n\nconst { Row, Col } = Grid;\n\nReactDOM.render(\n <div className=\"breakpoint-demo\">\n <div className=\"demo-title\">Resize browser to see how each column changes</div>\n <Row >\n <Col xs={12} s={8} m={6}>Col</Col>\n <Col xs={6} s={8} m={6}>Col</Col>\n <Col xs={6} s={8} m={12}>Col</Col>\n </Row>\n </div>, mountNode);
.breakpoint-demo .demo-title {\n margin-left: 20px;\n}\n\n.breakpoint-demo .next-row {\n margin: 10px 0;\n}\n\n.breakpoint-demo .next-col {\n border:1px solid #CCC;\n border-radius: 3px;\n background-color:#ECECEC;\n height: 30px;\n line-height: 30px;\n text-align: center;\n}
Use component
property to customize rendered type of the element.
import { Grid } from '@alifd/next';\n\nconst { Row, Col } = Grid;\n\nReactDOM.render(\n <div className=\"basic-demo\">\n <div className=\"demo-title\">Rendered as `ul` and `li`</div>\n <Row component=\"ul\">\n <Col span=\"12\" component=\"li\">col-12</Col>\n <Col span=\"12\" component=\"li\">col-12</Col>\n </Row>\n </div>, mountNode);
.basic-demo ul {\n list-style: none;\n padding: 0;\n}\n\n.basic-demo .demo-title {\n margin-left: 20px;\n}\n\n.basic-demo .next-row {\n margin: 10px 0;\n}\n\n.basic-demo .next-col {\n border:1px solid #CCC;\n border-radius: 3px;\n background-color:#ECECEC;\n height: 30px;\n line-height: 30px;\n text-align: center;\n}
使用 component
来指定需要渲染的元素类型,默认为 div
import { Grid } from '@alifd/next';\n\nconst { Row, Col } = Grid;\n\nReactDOM.render(\n <div className=\"basic-demo\">\n <div className=\"demo-title\">Rendered as `ul` and `li`</div>\n <Row component=\"ul\">\n <Col span=\"12\" component=\"li\">col-12</Col>\n <Col span=\"12\" component=\"li\">col-12</Col>\n </Row>\n </div>, mountNode);
.basic-demo ul {\n list-style: none;\n padding: 0;\n}\n\n.basic-demo .demo-title {\n margin-left: 20px;\n}\n\n.basic-demo .next-row {\n margin: 10px 0;\n}\n\n.basic-demo .next-col {\n border:1px solid #CCC;\n border-radius: 3px;\n background-color:#ECECEC;\n height: 30px;\n line-height: 30px;\n text-align: center;\n}
The fixedSpan
property of Col
specifies a column as a fixed-width column whose width is calculated as 20 * fixedSpan.
import { Grid } from '@alifd/next';\n\nconst { Row, Col } = Grid;\n\nReactDOM.render(\n <div className=\"mixin-demo\">\n <div className=\"demo-title\">Two-column layout, left column fixed, right column adaptive</div>\n <Row>\n <Col fixedSpan=\"16\">col-fixed-16</Col>\n <Col>col</Col>\n </Row>\n\n <div className=\"demo-title\">Two-column layout, right column fixed, left column adaptive</div>\n <Row>\n <Col>col</Col>\n <Col fixedSpan=\"16\">col-fixed-16</Col>\n </Row>\n\n <div className=\"demo-title\">Three-column layout, left column and right column fixed, middle column adaptive</div>\n <Row>\n <Col fixedSpan=\"8\">col-fixed-8</Col>\n <Col>col</Col>\n <Col fixedSpan=\"8\">col-fixed-8</Col>\n </Row>\n </div>, mountNode);
.mixin-demo .demo-title {\n margin-left: 20px;\n}\n\n.mixin-demo .next-row {\n margin: 10px 0;\n}\n\n.mixin-demo .next-col {\n border:1px solid #CCC;\n border-radius: 3px;\n background-color:#ECECEC;\n height: 30px;\n line-height: 30px;\n text-align: center;\n}
通过 Col
的 fixedSpan
属性来指定某列为固定宽度列,其宽度的计算方式为 20 * fixedSpan。
import { Grid } from '@alifd/next';\n\nconst { Row, Col } = Grid;\n\nReactDOM.render(\n <div className=\"mixin-demo\">\n <div className=\"demo-title\">Two-column layout, left column fixed, right column adaptive</div>\n <Row>\n <Col fixedSpan=\"16\">col-fixed-16</Col>\n <Col>col</Col>\n </Row>\n\n <div className=\"demo-title\">Two-column layout, right column fixed, left column adaptive</div>\n <Row>\n <Col>col</Col>\n <Col fixedSpan=\"16\">col-fixed-16</Col>\n </Row>\n\n <div className=\"demo-title\">Three-column layout, left column and right column fixed, middle column adaptive</div>\n <Row>\n <Col fixedSpan=\"8\">col-fixed-8</Col>\n <Col>col</Col>\n <Col fixedSpan=\"8\">col-fixed-8</Col>\n </Row>\n </div>, mountNode);
.mixin-demo .demo-title {\n margin-left: 20px;\n}\n\n.mixin-demo .next-row {\n margin: 10px 0;\n}\n\n.mixin-demo .next-col {\n border:1px solid #CCC;\n border-radius: 3px;\n background-color:#ECECEC;\n height: 30px;\n line-height: 30px;\n text-align: center;\n}
The spacing of the columns defaults to 0. You can change the column spacing by setting the gutter
property of Row
.
import { Range, Grid } from '@alifd/next';\n\nconst { Row, Col } = Grid;\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n gutter: 0\n };\n\n this.handleChange = this.handleChange.bind(this);\n }\n\n handleChange(gutter) {\n this.setState({\n gutter\n });\n }\n\n render() {\n const { gutter } = this.state;\n\n return (\n <div className=\"gutter-demo\">\n <Range value={gutter} onChange={this.handleChange} marks={4} step={4} max={16} hasTip={false} style={{ width: '400px', marginLeft: '20px', marginTop: '30px' }} />\n <Row gutter={gutter}>\n <Col span=\"6\"><div className=\"demo-col-inset\">col-6</div></Col>\n <Col span=\"6\"><div className=\"demo-col-inset\">col-6</div></Col>\n <Col span=\"6\"><div className=\"demo-col-inset\">col-6</div></Col>\n <Col span=\"6\"><div className=\"demo-col-inset\">col-6</div></Col>\n </Row>\n </div>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
.gutter-demo .demo-title {\n margin-left: 20px;\n}\n\n.gutter-demo .next-row {\n margin: 10px 0;\n}\n\n.gutter-demo .demo-col-inset {\n border:1px solid #CCC;\n border-radius: 3px;\n background-color:#ECECEC;\n height: 30px;\n line-height: 30px;\n text-align: center;\n}
列与列间距默认为0,可以通过设置 Row
的 gutter
属性来改变列间距。
import { Range, Grid } from '@alifd/next';\n\nconst { Row, Col } = Grid;\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n gutter: 0\n };\n\n this.handleChange = this.handleChange.bind(this);\n }\n\n handleChange(gutter) {\n this.setState({\n gutter\n });\n }\n\n render() {\n const { gutter } = this.state;\n\n return (\n <div className=\"gutter-demo\">\n <Range value={gutter} onChange={this.handleChange} marks={4} step={4} max={16} hasTip={false} style={{ width: '400px', marginLeft: '20px', marginTop: '30px' }} />\n <Row gutter={gutter}>\n <Col span=\"6\"><div className=\"demo-col-inset\">col-6</div></Col>\n <Col span=\"6\"><div className=\"demo-col-inset\">col-6</div></Col>\n <Col span=\"6\"><div className=\"demo-col-inset\">col-6</div></Col>\n <Col span=\"6\"><div className=\"demo-col-inset\">col-6</div></Col>\n </Row>\n </div>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
.gutter-demo .demo-title {\n margin-left: 20px;\n}\n\n.gutter-demo .next-row {\n margin: 10px 0;\n}\n\n.gutter-demo .demo-col-inset {\n border:1px solid #CCC;\n border-radius: 3px;\n background-color:#ECECEC;\n height: 30px;\n line-height: 30px;\n text-align: center;\n}
Provides a powerful responsive display and hide functionality under different breakpoints.
\n","order":"6"},"codes":{"jsx":"import { Grid } from '@alifd/next';\n\nconst { Row, Col } = Grid;\n\nReactDOM.render(\nimport { Grid } from '@alifd/next';\n\nconst { Row, Col } = Grid;\n\nReactDOM.render(\n <div className=\"hidden-demo\">\n <div className=\"demo-title\">Hide columns under all breakpoints, resize browser to see if the second column is hidden or shown</div>\n <Row>\n <Col span=\"8\">col-8</Col>\n <Col span=\"16\" hidden>col-16</Col>\n </Row>\n\n <div className=\"demo-title\">Hide columns under a breakpoint such as xs, resize browser to see if the second column is hidden or shown</div>\n <Row>\n <Col span=\"8\">col-8</Col>\n <Col span=\"16\" hidden=\"xs\">col-16</Col>\n </Row>\n\n <div className=\"demo-title\">Hide columns under some breakpoints such as xs and s, resize browser to see if the second column is hidden or shown</div>\n <Row>\n <Col span=\"8\">col-8</Col>\n <Col span=\"16\" hidden={['xs', 's']}>col-16</Col>\n </Row>\n </div>, mountNode);
.hidden-demo .demo-title {\n margin-left: 20px;\n}\n\n.hidden-demo .next-row {\n margin: 10px 0;\n}\n\n.hidden-demo .next-col {\n border:1px solid #CCC;\n border-radius: 3px;\n background-color:#ECECEC;\n height: 30px;\n line-height: 30px;\n text-align: center;\n}
提供了强大的响应式的显示与隐藏功能,支持在不同断点下的显示与隐藏。
\n","order":"6"},"codes":{"jsx":"import { Grid } from '@alifd/next';\n\nconst { Row, Col } = Grid;\n\nReactDOM.render(\nimport { Grid } from '@alifd/next';\n\nconst { Row, Col } = Grid;\n\nReactDOM.render(\n <div className=\"hidden-demo\">\n <div className=\"demo-title\">Hide columns under all breakpoints, resize browser to see if the second column is hidden or shown</div>\n <Row>\n <Col span=\"8\">col-8</Col>\n <Col span=\"16\" hidden>col-16</Col>\n </Row>\n\n <div className=\"demo-title\">Hide columns under a breakpoint such as xs, resize browser to see if the second column is hidden or shown</div>\n <Row>\n <Col span=\"8\">col-8</Col>\n <Col span=\"16\" hidden=\"xs\">col-16</Col>\n </Row>\n\n <div className=\"demo-title\">Hide columns under some breakpoints such as xs and s, resize browser to see if the second column is hidden or shown</div>\n <Row>\n <Col span=\"8\">col-8</Col>\n <Col span=\"16\" hidden={['xs', 's']}>col-16</Col>\n </Row>\n </div>, mountNode);
.hidden-demo .demo-title {\n margin-left: 20px;\n}\n\n.hidden-demo .next-row {\n margin: 10px 0;\n}\n\n.hidden-demo .next-col {\n border:1px solid #CCC;\n border-radius: 3px;\n background-color:#ECECEC;\n height: 30px;\n line-height: 30px;\n text-align: center;\n}
(IE9 is not supported) Based on Flex's justify-content attributes, set the justify
property on Row
to control the horizontal alignment: start (left-aligned, default), center (center-aligned),end (right-aligned), space-between (both-aligned, spacing between items are all the same), space-around (equal intervals on both sides, the spacing between columns is double the spacing between the column and the left and right ends).
import { Grid } from '@alifd/next';\n\nconst { Row, Col } = Grid;\n\nReactDOM.render(\n <div className=\"justify-demo\">\n <div className=\"demo-title\">start</div>\n <Row justify=\"start\">\n <Col span=\"4\">col-4</Col>\n <Col span=\"4\">col-4</Col>\n <Col span=\"4\">col-4</Col>\n </Row>\n\n <div className=\"demo-title\">center</div>\n <Row justify=\"center\">\n <Col span=\"4\">col-4</Col>\n <Col span=\"4\">col-4</Col>\n <Col span=\"4\">col-4</Col>\n </Row>\n\n <div className=\"demo-title\">end</div>\n <Row justify=\"end\">\n <Col span=\"4\">col-4</Col>\n <Col span=\"4\">col-4</Col>\n <Col span=\"4\">col-4</Col>\n </Row>\n\n <div className=\"demo-title\">space-between</div>\n <Row justify=\"space-between\">\n <Col span=\"4\">col-4</Col>\n <Col span=\"4\">col-4</Col>\n <Col span=\"4\">col-4</Col>\n </Row>\n\n <div className=\"demo-title\">space-around</div>\n <Row justify=\"space-around\">\n <Col span=\"4\">col-4</Col>\n <Col span=\"4\">col-4</Col>\n <Col span=\"4\">col-4</Col>\n </Row>\n </div>, mountNode);
.justify-demo .demo-title {\n margin-left: 20px;\n}\n\n.justify-demo .next-row {\n margin: 10px 0;\n}\n\n.justify-demo .next-col {\n border:1px solid #CCC;\n border-radius: 3px;\n background-color:#ECECEC;\n height: 30px;\n line-height: 30px;\n text-align: center;\n}
(不支持 IE9 浏览器)基于 Flex 的 justify-content 属性实现,在 Row
上设置 justify
属性,即可行内多列水平方向对齐方式:start(左对齐,默认),center(居中对齐),end(右对齐),space-between(两端对齐,项目之间的间隔都相),space-around(两侧的间隔相等,列之间的间隔比列与左右两端的间隔大一倍)。
import { Grid } from '@alifd/next';\n\nconst { Row, Col } = Grid;\n\nReactDOM.render(\n <div className=\"justify-demo\">\n <div className=\"demo-title\">start</div>\n <Row justify=\"start\">\n <Col span=\"4\">col-4</Col>\n <Col span=\"4\">col-4</Col>\n <Col span=\"4\">col-4</Col>\n </Row>\n\n <div className=\"demo-title\">center</div>\n <Row justify=\"center\">\n <Col span=\"4\">col-4</Col>\n <Col span=\"4\">col-4</Col>\n <Col span=\"4\">col-4</Col>\n </Row>\n\n <div className=\"demo-title\">end</div>\n <Row justify=\"end\">\n <Col span=\"4\">col-4</Col>\n <Col span=\"4\">col-4</Col>\n <Col span=\"4\">col-4</Col>\n </Row>\n\n <div className=\"demo-title\">space-between</div>\n <Row justify=\"space-between\">\n <Col span=\"4\">col-4</Col>\n <Col span=\"4\">col-4</Col>\n <Col span=\"4\">col-4</Col>\n </Row>\n\n <div className=\"demo-title\">space-around</div>\n <Row justify=\"space-around\">\n <Col span=\"4\">col-4</Col>\n <Col span=\"4\">col-4</Col>\n <Col span=\"4\">col-4</Col>\n </Row>\n </div>, mountNode);
.justify-demo .demo-title {\n margin-left: 20px;\n}\n\n.justify-demo .next-row {\n margin: 10px 0;\n}\n\n.justify-demo .next-col {\n border:1px solid #CCC;\n border-radius: 3px;\n background-color:#ECECEC;\n height: 30px;\n line-height: 30px;\n text-align: center;\n}
Row
can also be nested under Col
to create a more detailed layout.
import { Grid } from '@alifd/next';\n\nconst { Row, Col } = Grid;\n\nReactDOM.render(\n <div className=\"nest-demo\">\n <Row className=\"demo-row\">\n <Col span=\"10\">\n <Row>\n <Col span=\"6\">\n <div className=\"demo-col-inset\">col-10-6</div>\n </Col>\n <Col span=\"18\">\n <div className=\"demo-col-inset\">col-10-18</div>\n </Col>\n </Row>\n </Col>\n <Col span=\"14\">\n <Row>\n <Col span=\"18\">\n <div className=\"demo-col-inset\">col-14-18</div>\n </Col>\n <Col span=\"6\">\n <div className=\"demo-col-inset\">col-14-6</div>\n </Col>\n </Row>\n </Col>\n </Row>\n </div>, mountNode);
.nest-demo .demo-title {\n margin-left: 20px;\n}\n\n.nest-demo .demo-row {\n margin: 10px 0;\n}\n\n.nest-demo .demo-col-inset {\n border:1px solid #CCC;\n border-radius: 3px;\n background-color:#ECECEC;\n height: 30px;\n line-height: 30px;\n text-align: center;\n}
Col
下也可嵌套 Row
,以完成更细致的布局。
import { Grid } from '@alifd/next';\n\nconst { Row, Col } = Grid;\n\nReactDOM.render(\n <div className=\"nest-demo\">\n <Row className=\"demo-row\">\n <Col span=\"10\">\n <Row>\n <Col span=\"6\">\n <div className=\"demo-col-inset\">col-10-6</div>\n </Col>\n <Col span=\"18\">\n <div className=\"demo-col-inset\">col-10-18</div>\n </Col>\n </Row>\n </Col>\n <Col span=\"14\">\n <Row>\n <Col span=\"18\">\n <div className=\"demo-col-inset\">col-14-18</div>\n </Col>\n <Col span=\"6\">\n <div className=\"demo-col-inset\">col-14-6</div>\n </Col>\n </Row>\n </Col>\n </Row>\n </div>, mountNode);
.nest-demo .demo-title {\n margin-left: 20px;\n}\n\n.nest-demo .demo-row {\n margin: 10px 0;\n}\n\n.nest-demo .demo-col-inset {\n border:1px solid #CCC;\n border-radius: 3px;\n background-color:#ECECEC;\n height: 30px;\n line-height: 30px;\n text-align: center;\n}
(IE9 is not supported) Column can be offset to the right by a fixed distance that is calculated in the same way as a fixed-width column.
\n","order":"9"},"codes":{"jsx":"import { Grid } from '@alifd/next';\n\nconst { Row, Col } = Grid;\n\nReactDOM.render(\nimport { Grid } from '@alifd/next';\n\nconst { Row, Col } = Grid;\n\nReactDOM.render(\n <div className=\"offset-fixed-demo\">\n <div className=\"demo-title\">Normal offset, set offset from 1 to 30</div>\n <Row>\n <Col fixedOffset=\"0\">offset-fixed-0</Col>\n </Row>\n <Row>\n <Col fixedOffset=\"4\">offset-fixed-4</Col>\n </Row>\n <Row>\n <Col fixedOffset=\"8\">offset-fixed-8</Col>\n </Row>\n <Row>\n <Col fixedOffset=\"12\">offset-fixed-12</Col>\n </Row>\n\n <div className=\"demo-title\">Adaptive offset</div>\n <Row>\n <Col>col</Col>\n <Col fixedOffset=\"12\">offset-fixed-12</Col>\n </Row>\n </div>, mountNode\n);
.offset-fixed-demo .demo-title {\n margin-left: 20px;\n}\n\n.offset-fixed-demo .next-row {\n margin: 10px 0;\n}\n\n.offset-fixed-demo .next-col {\n border:1px solid #CCC;\n border-radius: 3px;\n background-color:#ECECEC;\n height: 30px;\n line-height: 30px;\n text-align: center;\n}
(不支持 IE9 浏览器)列可以向右偏移一定距离,该距离的计算方式和固定宽度列的宽度相同。
\n","order":"9"},"codes":{"jsx":"import { Grid } from '@alifd/next';\n\nconst { Row, Col } = Grid;\n\nReactDOM.render(\nimport { Grid } from '@alifd/next';\n\nconst { Row, Col } = Grid;\n\nReactDOM.render(\n <div className=\"offset-fixed-demo\">\n <div className=\"demo-title\">Normal offset, set offset from 1 to 30</div>\n <Row>\n <Col fixedOffset=\"0\">offset-fixed-0</Col>\n </Row>\n <Row>\n <Col fixedOffset=\"4\">offset-fixed-4</Col>\n </Row>\n <Row>\n <Col fixedOffset=\"8\">offset-fixed-8</Col>\n </Row>\n <Row>\n <Col fixedOffset=\"12\">offset-fixed-12</Col>\n </Row>\n\n <div className=\"demo-title\">Adaptive offset</div>\n <Row>\n <Col>col</Col>\n <Col fixedOffset=\"12\">offset-fixed-12</Col>\n </Row>\n </div>, mountNode\n);
.offset-fixed-demo .demo-title {\n margin-left: 20px;\n}\n\n.offset-fixed-demo .next-row {\n margin: 10px 0;\n}\n\n.offset-fixed-demo .next-col {\n border:1px solid #CCC;\n border-radius: 3px;\n background-color:#ECECEC;\n height: 30px;\n line-height: 30px;\n text-align: center;\n}
(IE9 is not supported) Column can be offset to the right by a distance that is calculated in the same way as a column.
\n","order":"8"},"codes":{"jsx":"import { Grid } from '@alifd/next';\n\nconst { Row, Col } = Grid;\n\nReactDOM.render(\nimport { Grid } from '@alifd/next';\n\nconst { Row, Col } = Grid;\n\nReactDOM.render(\n <div className=\"offset-demo\">\n <div className=\"demo-title\">Normal offset, set offset from 1 to 24</div>\n <Row>\n <Col offset=\"0\">offset-0</Col>\n </Row>\n <Row>\n <Col offset=\"4\">offset-4</Col>\n </Row>\n <Row>\n <Col offset=\"8\">offset-8</Col>\n </Row>\n <Row>\n <Col offset=\"12\">offset-12</Col>\n </Row>\n\n <div className=\"demo-title\">Adaptive offset</div>\n <Row>\n <Col>col</Col>\n <Col offset=\"12\">offset-12</Col>\n </Row>\n </div>,\n mountNode\n);
.offset-demo .demo-title {\n margin-left: 20px;\n}\n\n.offset-demo .next-row {\n margin: 10px 0;\n}\n\n.offset-demo .next-col {\n border:1px solid #CCC;\n border-radius: 3px;\n background-color:#ECECEC;\n height: 30px;\n line-height: 30px;\n text-align: center;\n}
(不支持 IE9 浏览器)列可以向右偏移一定距离,该距离的计算方式和列所占宽度计算方式相同。
\n","order":"8"},"codes":{"jsx":"import { Grid } from '@alifd/next';\n\nconst { Row, Col } = Grid;\n\nReactDOM.render(\nimport { Grid } from '@alifd/next';\n\nconst { Row, Col } = Grid;\n\nReactDOM.render(\n <div className=\"offset-demo\">\n <div className=\"demo-title\">Normal offset, set offset from 1 to 24</div>\n <Row>\n <Col offset=\"0\">offset-0</Col>\n </Row>\n <Row>\n <Col offset=\"4\">offset-4</Col>\n </Row>\n <Row>\n <Col offset=\"8\">offset-8</Col>\n </Row>\n <Row>\n <Col offset=\"12\">offset-12</Col>\n </Row>\n\n <div className=\"demo-title\">Adaptive offset</div>\n <Row>\n <Col>col</Col>\n <Col offset=\"12\">offset-12</Col>\n </Row>\n </div>,\n mountNode\n);
.offset-demo .demo-title {\n margin-left: 20px;\n}\n\n.offset-demo .next-row {\n margin: 10px 0;\n}\n\n.offset-demo .next-col {\n border:1px solid #CCC;\n border-radius: 3px;\n background-color:#ECECEC;\n height: 30px;\n line-height: 30px;\n text-align: center;\n}
The default width of the Row
is set to 100%. You can set the fixed
property to true so that the width of Row
does not immediately change with the size of the viewport. Instead, it is maintained at a certain breakpoint. You can also set the fixedWidth
property to a certain breakpoint value, thus fixing the width of Row
, no longer changing with the size of the viewport.
import { Grid } from '@alifd/next';\n\nconst { Row, Col } = Grid;\n\nconst breakpoints = {\n xxs: 320,\n xs: 480,\n s: 720,\n m: 990,\n l: 1200,\n xl: 1500\n};\n\nclass Demo extends React.Component {\n componentDidMount() {\n const row = ReactDOM.findDOMNode(this.refs.fixCol);\n\n this.handleResize = () => {\n let point = '';\n const innerWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;\n const keys = Object.keys(breakpoints);\n for (let i = 0; i < keys.length; i++) {\n const width = breakpoints[keys[i]];\n const nextWidth = breakpoints[keys[i + 1]];\n if (innerWidth > width && (innerWidth < nextWidth || !nextWidth)) {\n point = keys[i];\n break;\n }\n }\n\n if (point) {\n row.innerHTML = `${breakpoints[point]}px`;\n }\n };\n window.addEventListener('resize', this.handleResize);\n\n this.handleResize();\n }\n\n componentWillUnmount() {\n window.removeListener('resize', this.handleResize);\n }\n\n render() {\n return (\n <div className=\"type-demo\">\n <div className=\"demo-title\">Default</div>\n <Row>\n <Col>100%</Col>\n </Row>\n <div className=\"demo-title\">Set fixed to true</div>\n <Row ref=\"fixedRow\" fixed>\n <Col ref=\"fixCol\" />\n </Row>\n <div className=\"demo-title\">Set fixedWidth to 's'</div>\n <Row fixedWidth=\"s\">\n <Col>720px</Col>\n </Row>\n </div>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
.type-demo .demo-title {\n margin-left: 20px;\n}\n\n.type-demo .next-row {\n margin: 10px 0;\n}\n\n.type-demo .next-col {\n border:1px solid #CCC;\n border-radius: 3px;\n background-color:#ECECEC;\n height: 30px;\n line-height: 30px;\n text-align: center;\n}
默认 Row
的宽度被设置为100%,可以通过设置 fixed
属性为 true,来让 Row
的宽度不立刻随着是视口大小变动而变动,而是在某个断点下维持固定的宽度,也可以通过设置 fixedWidth
属性为某一断点值,从而固定 Row
的宽度,不再随着视口大小变动而变动。
import { Grid } from '@alifd/next';\n\nconst { Row, Col } = Grid;\n\nconst breakpoints = {\n xxs: 320,\n xs: 480,\n s: 720,\n m: 990,\n l: 1200,\n xl: 1500\n};\n\nclass Demo extends React.Component {\n componentDidMount() {\n const row = ReactDOM.findDOMNode(this.refs.fixCol);\n\n this.handleResize = () => {\n let point = '';\n const innerWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;\n const keys = Object.keys(breakpoints);\n for (let i = 0; i < keys.length; i++) {\n const width = breakpoints[keys[i]];\n const nextWidth = breakpoints[keys[i + 1]];\n if (innerWidth > width && (innerWidth < nextWidth || !nextWidth)) {\n point = keys[i];\n break;\n }\n }\n\n if (point) {\n row.innerHTML = `${breakpoints[point]}px`;\n }\n };\n window.addEventListener('resize', this.handleResize);\n\n this.handleResize();\n }\n\n componentWillUnmount() {\n window.removeListener('resize', this.handleResize);\n }\n\n render() {\n return (\n <div className=\"type-demo\">\n <div className=\"demo-title\">Default</div>\n <Row>\n <Col>100%</Col>\n </Row>\n <div className=\"demo-title\">Set fixed to true</div>\n <Row ref=\"fixedRow\" fixed>\n <Col ref=\"fixCol\" />\n </Row>\n <div className=\"demo-title\">Set fixedWidth to 's'</div>\n <Row fixedWidth=\"s\">\n <Col>720px</Col>\n </Row>\n </div>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
.type-demo .demo-title {\n margin-left: 20px;\n}\n\n.type-demo .next-row {\n margin: 10px 0;\n}\n\n.type-demo .next-col {\n border:1px solid #CCC;\n border-radius: 3px;\n background-color:#ECECEC;\n height: 30px;\n line-height: 30px;\n text-align: center;\n}
(IE9 is not supported) Default the column is no longer wrapped when the width overflows. If you want to wrap automatically, set wrap
of Row
to true.
import { Grid } from '@alifd/next';\n\nconst { Row, Col } = Grid;\n\nReactDOM.render(\n <div className=\"wrap-demo\">\n <div className=\"demo-title\">No wrap</div>\n <Row>\n <Col span=\"6\">col-6</Col>\n <Col span=\"6\">col-6</Col>\n <Col span=\"6\">col-6</Col>\n <Col span=\"8\">col-8</Col>\n </Row>\n <div className=\"demo-title\">Wrap</div>\n <Row wrap>\n <Col span=\"6\">col-6</Col>\n <Col span=\"6\">col-6</Col>\n <Col span=\"6\">col-6</Col>\n <Col span=\"8\">col-8</Col>\n </Row>\n </div>, mountNode);
.wrap-demo .demo-title {\n margin-left: 20px;\n}\n\n.wrap-demo .next-row {\n margin: 10px 0;\n}\n\n.wrap-demo .next-col {\n border:1px solid #CCC;\n border-radius: 3px;\n background-color:#ECECEC;\n height: 30px;\n line-height: 30px;\n text-align: center;\n}
(不支持 IE9 浏览器)默认列在行中宽度溢出后不会换行,如果想自动换行,请为 Row
设置 wrap
为 true。
import { Grid } from '@alifd/next';\n\nconst { Row, Col } = Grid;\n\nReactDOM.render(\n <div className=\"wrap-demo\">\n <div className=\"demo-title\">No wrap</div>\n <Row>\n <Col span=\"6\">col-6</Col>\n <Col span=\"6\">col-6</Col>\n <Col span=\"6\">col-6</Col>\n <Col span=\"8\">col-8</Col>\n </Row>\n <div className=\"demo-title\">Wrap</div>\n <Row wrap>\n <Col span=\"6\">col-6</Col>\n <Col span=\"6\">col-6</Col>\n <Col span=\"6\">col-6</Col>\n <Col span=\"8\">col-8</Col>\n </Row>\n </div>, mountNode);
.wrap-demo .demo-title {\n margin-left: 20px;\n}\n\n.wrap-demo .next-row {\n margin: 10px 0;\n}\n\n.wrap-demo .next-col {\n border:1px solid #CCC;\n border-radius: 3px;\n background-color:#ECECEC;\n height: 30px;\n line-height: 30px;\n text-align: center;\n}
This grid system provides response rules for almost all mainstream resolution scenes such as 320, 480, 720, 990, 1200, and 1500. The responsive grids are implemented using a 24-column and a 5-point to meet 2, 3, 4, 5, and 6 ratio layouts. The fixed grid uses a 20px width as the unit, it is recommended to use 9, 10, 12, 14, 16, 18, 24, but all from 1 to 30 are also available. You can also customize the fixed grid columns according to your requirements. The breakpoint are: xss(320px), xs(480px), s(720px), m(990px), l(1200px), xl(1500px). Based on the Flex implementation, IE9 is compatible with display:table;
, but IE9 only supports basic responsive layouts (see API and DEMO for details).
Though we have build-in support of a11y by adding <Row>
and <Col>
with role="row"
and role="gridcell"
respectively, in order to achieve more a11y compliance, developers are also expected to add role="grid"
in the outer wrapper element, as this:
<div role="grid">\n <Row><Col span={6}>1</Col><Col span={6}>2</Col><Col span={6}>3</Col><Col span={6}>4</Col></Row>\n <Row><Col span={6} offset={6}>1</Col><Col span={6} offset={6}>2</Col></Row>\n</div>
Param | \nDescripiton | \nType | \nDefault Value | \n
---|---|---|---|
children | \ncontent of the row | \nReactNode | \n- | \n
gutter | \nspacing of the columns | \nString/Number | \n0 | \n
wrap | \nwhether the row is wrap while width overflow | \nBoolean | \nfalse | \n
fixed | \nwhether the width of the row stays the same under a certain breakpoint (the default row width varies depending on the viewport) | \nBoolean | \nfalse | \n
fixedWidth | \nthe width of the fixed row is the width of a certain breakpoint and it is not affected by the viewport. option: 'xxs'(320px) 'xs'(480px) 's'(720px) 'm'(990px) 'l'(1200px) 'xl'(1500px) | \nEnum | \n- | \n
align | \n(IE9 is not supported) vertical alignment of columns option: 'top' 'center' 'bottom' 'baseline' 'stretch' | \nEnum | \n'stretch' | \n
justify | \n(IE9 is not supported) horizontal alignment of columns option: 'start' 'center' 'end' 'space-between' 'space-around' | \nEnum | \n'start' | \n
hidden | \nwhether display or hide the row under different breakpoints. option: true(always hide) false(always display) 'xs'(hide under xs breakpoint) ['xxs', 'xs', 's', 'm', 'l', 'xl'](hide under xxs, xs, s, m, l, xl breakpoint) | \nBoolean/String/Array | \n- | \n
Param | \nDescripiton | \nType | \nDefault Value | \n
---|---|---|---|
children | \ncontent of the column | \nReactNode | \n- | \n
span | \nwidth of the column option: 1, 2, 3, ..., 22, 23, 24 | \nString/Number | \n- | \n
fixedSpan | \nwidth of the fixed column, the unit width is 20px option: 1, 2, 3, ..., 28, 29, 30 | \nString/Number | \n- | \n
offset | \n(IE9 is not supported) the offset of the column option: 1, 2, 3, ..., 22, 23, 24 | \nString/Number | \n- | \n
fixedOffset | \n(IE9 is not supported) the fixed offset of the column, the unit width is 20px option: 1, 2, 3, ..., 28, 29, 30 | \nString/Number | \n- | \n
align | \n(IE9 is not supported) vertical alignment of columns, it can override the Row's align property option: 'top', 'center', 'bottom', 'baseline', 'stretch' | \nEnum | \n- | \n
hidden | \nwhether display or hide the column under different breakpoints. option: true(always hide) false(always display) 'xs'(hide under xs breakpoint) ['xxs', 'xs', 's', 'm', 'l', 'xl'](hide under xxs, xs, s, m, l, xl breakpoint) | \nBoolean/String/Array | \n- | \n
xxs | \n>=320px, responsive grid, it can be a span string or an object with span and offset property | \nString/Number/Object | \n- | \n
xs | \n>=480px, responsive grid, it can be a span string or an object with span and offset property | \nString/Number/Object | \n- | \n
s | \n>=720px, responsive grid, it can be a span string or an object with span and offset property | \nString/Number/Object | \n- | \n
m | \n>=990px, responsive grid, it can be a span string or an object with span and offset property | \nString/Number/Object | \n- | \n
l | \n>=1200px, responsive grid, it can be a span string or an object with span and offset property | \nString/Number/Object | \n- | \n
xl | \n>=1500px, responsive grid, it can be a span string or an object with span and offset property | \nString/Number/Object | \n- | \n
component | \nrender node 'div' | \nString | \n'div' | \n
此栅格系统提供了320,480,720, 990,1200,1500等几乎所有主流分辨率场景的响应规则。
\n响应式栅格采用24列栅格体系和5分比实现,以满足2,3,4,5,6分比布局等多种情况。
\n固定栅格采用 20px 宽度作为单位栅格, 推荐使用9,10,12,14,16,18,24,但同时也提供了从1到30的所有栅格,也可根据需求定制固定栅格列。
\n响应式断点阈值为:xss(320px), xs(480px), s(720px), m(990px), l(1200px), xl(1500px)。
\n基于Flex实现,对 IE9 通过 display:table;
兼容实现,但 IE9 仅支持基本的响应式布局(详情请参考 API 和 DEMO 的说明)。
默认 <Row>
和 <Col>
会加上 role="row"
和 role="gridcell"
, 但是为了完美的无障碍实现, 开发者还应该在外部容器加上 role="grid"
。示例代码如下:
<div role="grid">\n <Row><Col span={6}>1</Col><Col span={6}>2</Col><Col span={6}>3</Col><Col span={6}>4</Col></Row>\n <Row><Col span={6} offset={6}>1</Col><Col span={6} offset={6}>2</Col></Row>\n</div>\n\n
参数 | \n说明 | \n类型 | \n默认值 | \n
---|---|---|---|
children | \n行内容 | \nReactNode | \n- | \n
gutter | \n列间隔 | \nString/Number | \n0 | \n
wrap | \n列在行中宽度溢出后是否换行 | \nBoolean | \nfalse | \n
fixed | \n行在某一断点下宽度是否保持不变(默认行宽度随视口变化而变化) | \nBoolean | \nfalse | \n
fixedWidth | \n固定行的宽度为某一断点的宽度,不受视口影响而变动 可选值: 'xxs'(320px) 'xs'(480px) 's'(720px) 'm'(990px) 'l'(1200px) 'xl'(1500px) | \nEnum | \n- | \n
align | \n(不支持IE9浏览器)多列垂直方向对齐方式 可选值: 'top'(顶部对齐) 'center'(居中对齐) 'bottom'(底部对齐) 'baseline'(按第一行文字基线对齐) 'stretch'(未设置高度或设为 auto,将占满整个容器的高度) | \nEnum | \n- | \n
justify | \n(不支持IE9浏览器)行内具有多余空间时的布局方式 可选值: 'start'(左对齐) 'center'(居中对齐) 'end'(右对齐) 'space-between'(两端对齐,列之间间距相等) 'space-around'(每列具有相同的左右间距,行两端间距是列间距的二分之一) | \nEnum | \n- | \n
hidden | \n行在不同断点下的显示与隐藏 可选值: true(在所有断点下隐藏) false(在所有断点下显示) 'xs'(在 xs 断点下隐藏) ['xxs', 'xs', 's', 'm', 'l', 'xl'](在 xxs, xs, s, m, l, xl 断点下隐藏) | \nBoolean/String/Array | \n- | \n
component | \n指定以何种元素渲染该节点 - 默认为 'div' | \nString/Function | \n'div' | \n
参数 | \n说明 | \n类型 | \n默认值 | \n
---|---|---|---|
children | \n列内容 | \nReactNode | \n- | \n
span | \n列宽度 可选值: 1, 2, 3, ..., 22, 23, 24 | \nString/Number | \n- | \n
fixedSpan | \n固定列宽度,宽度值为20 * 栅格数 可选值: 1, 2, 3, ..., 28, 29, 30 | \nString/Number | \n- | \n
offset | \n(不支持IE9浏览器)列偏移 可选值: 1, 2, 3, ..., 22, 23, 24 | \nString/Number | \n- | \n
fixedOffset | \n(不支持IE9浏览器)固定列偏移,宽度值为20 * 栅格数 可选值: 1, 2, 3, ..., 28, 29, 30 | \nString/Number | \n- | \n
align | \n(不支持IE9浏览器)多列垂直方向对齐方式,可覆盖Row的align属性 可选值: 'top', 'center', 'bottom', 'baseline', 'stretch' | \nEnum | \n- | \n
hidden | \n列在不同断点下的显示与隐藏 可选值: true(在所有断点下隐藏) false(在所有断点下显示) 'xs'(在 xs 断点下隐藏) ['xxs', 'xs', 's', 'm', 'l', 'xl'](在 xxs, xs, s, m, l, xl 断点下隐藏) | \nBoolean/String/Array | \n- | \n
xxs | \n>=320px,响应式栅格,可为栅格数(span)或一个包含栅格数(span)和偏移栅格数(offset)对象 | \nString/Number/Object | \n- | \n
xs | \n>=480px,响应式栅格,可为栅格数(span)或一个包含栅格数(span)和偏移栅格数(offset)对象 | \nString/Number/Object | \n- | \n
s | \n>=720px,响应式栅格,可为栅格数(span)或一个包含栅格数(span)和偏移栅格数(offset)对象 | \nString/Number/Object | \n- | \n
m | \n>=990px,响应式栅格,可为栅格数(span)或一个包含栅格数(span)和偏移栅格数(offset)对象 | \nString/Number/Object | \n- | \n
l | \n>=1200px,响应式栅格,可为栅格数(span)或一个包含栅格数(span)和偏移栅格数(offset)对象 | \nString/Number/Object | \n- | \n
xl | \n>=1500px,响应式栅格,可为栅格数(span)或一个包含栅格数(span)和偏移栅格数(offset)对象 | \nString/Number/Object | \n- | \n
component | \n指定以何种元素渲染该节点,默认为 'div' | \nString/Function | \n'div' | \n
If it's a decorative icon, set aria-hidden
to ignore; Or it's a button, set role="button"
and aria-label
.
\nimport { Icon } from '@alifd/next';\n\nReactDOM.render(<div>\n button: <br/>\n <Icon type=\"atm\" role=\"button\" aria-label=\"icon atm\" style={{ margin:'5px' }}/>\n <Icon type=\"smile\" role=\"button\" aria-label=\"icon smile\" style={{ margin:'5px' }}/>\n <br/>\n decoration: <br/>\n <Icon type=\"success\" aria-hidden style={{ margin:'5px' }}/>\n</div>, mountNode);\n
若为装饰性icon,请设置通过设置 aria-hidden
忽略;若为按钮类型icon,请务必设置 role="button"
和 aria-label
。
\nimport { Icon } from '@alifd/next';\n\nReactDOM.render(<div>\n button: <br/>\n <Icon type=\"atm\" role=\"button\" aria-label=\"icon atm\" style={{ margin:'5px' }}/>\n <Icon type=\"smile\" role=\"button\" aria-label=\"icon smile\" style={{ margin:'5px' }}/>\n <br/>\n decoration: <br/>\n <Icon type=\"success\" aria-hidden style={{ margin:'5px' }}/>\n</div>, mountNode);\n
Basic usage of Icon。
\n","order":"0"},"codes":{"jsx":"import { Icon } from '@alifd/next';\n\nReactDOM.render(import { Icon } from '@alifd/next';\n\nReactDOM.render(<Icon type=\"atm\" />, mountNode);
展示图标基本使用方法。
\n","order":"0"},"codes":{"jsx":"import { Icon } from '@alifd/next';\n\nReactDOM.render(import { Icon } from '@alifd/next';\n\nReactDOM.render(<Icon type=\"atm\" />, mountNode);
ICON's sizes include:xxs
,xs
,small
,medium
,large
,xl
,xxl
,xxxl
, inherit
。
import { Icon } from '@alifd/next';\n\nconst sizes = ['xxs', 'xs', 'small', 'medium', 'large', 'xl', 'xxl', 'xxxl'];\nconst inherit = 'inherit';\nReactDOM.render((\n <div>\n <ul className=\"icon-sizes\">\n {sizes.map((size, index) => (\n <li key={index}>\n <Icon type=\"smile\" size={size} />\n <span>{size}</span>\n </li>))}\n </ul>\n\n <span>{inherit}</span>\n <h4>\n Shall I compare thee to a summer's day? <Icon type=\"smile\" size={inherit} /> <Icon type=\"set\" size={inherit} />\n </h4>\n <h3>\n Thou art more lovely and more temperate. <Icon type=\"smile\" size={inherit} /> <Icon type=\"set\" size={inherit} />\n </h3>\n <h2>\n Rough winds do shake the darling buds of May, <Icon type=\"smile\" size={inherit} /> <Icon type=\"set\" size={inherit} />\n </h2>\n <h1>\n And summer's lease hath all too short a date. <Icon type=\"smile\" size={inherit} /> <Icon type=\"set\" size={inherit} />\n </h1>\n </div>\n), mountNode);\n
.icon-sizes {\n margin: 0;\n padding: 0;\n list-style: none;\n}\n\n.icon-sizes li {\n display: inline-block;\n width: 80px;\n height: 80px;\n}\n\n.icon-sizes i {\n display: block;\n margin: 12px auto 0 auto;\n text-align: center;\n}\n\n.icon-sizes span {\n display: block;\n margin-top: 10px;\n text-align: center;\n}
ICON的尺寸包括:xxs
,xs
,small
,medium
,large
,xl
,xxl
,xxxl
, inherit
。
import { Icon } from '@alifd/next';\n\nconst sizes = ['xxs', 'xs', 'small', 'medium', 'large', 'xl', 'xxl', 'xxxl'];\nconst inherit = 'inherit';\nReactDOM.render((\n <div>\n <ul className=\"icon-sizes\">\n {sizes.map((size, index) => (\n <li key={index}>\n <Icon type=\"smile\" size={size} />\n <span>{size}</span>\n </li>))}\n </ul>\n\n <span>{inherit}</span>\n <h4>\n Shall I compare thee to a summer's day? <Icon type=\"smile\" size={inherit} /> <Icon type=\"set\" size={inherit} />\n </h4>\n <h3>\n Thou art more lovely and more temperate. <Icon type=\"smile\" size={inherit} /> <Icon type=\"set\" size={inherit} />\n </h3>\n <h2>\n Rough winds do shake the darling buds of May, <Icon type=\"smile\" size={inherit} /> <Icon type=\"set\" size={inherit} />\n </h2>\n <h1>\n And summer's lease hath all too short a date. <Icon type=\"smile\" size={inherit} /> <Icon type=\"set\" size={inherit} />\n </h1>\n </div>\n), mountNode);\n
.icon-sizes {\n margin: 0;\n padding: 0;\n list-style: none;\n}\n\n.icon-sizes li {\n display: inline-block;\n width: 80px;\n height: 80px;\n}\n\n.icon-sizes i {\n display: block;\n margin: 12px auto 0 auto;\n text-align: center;\n}\n\n.icon-sizes span {\n display: block;\n margin-top: 10px;\n text-align: center;\n}
Icon fonts are essentially text. You can use style
and className
to set the size and color of the icons.
import { Icon } from '@alifd/next';\n\nReactDOM.render(\n <div>\n <div className=\"icon-style-demo\">\n <Icon type=\"success\" style={{ color: '#1DC11D', marginRight: '10px' }} />\n This is a success message!\n </div>\n <div className=\"icon-style-demo\">\n <Icon type=\"warning\" style={{ color: '#FFA003', marginRight: '10px' }} />\n This is a warning message!\n </div>\n <div className=\"icon-style-demo\">\n <Icon type=\"error\" style={{ color: '#FF3333', marginRight: '10px' }} />\n This is a failure message!\n </div>\n </div>\n , mountNode);
.icon-style-demo {\n height: 24px;\n line-height: 24px;\n margin-bottom: 10px;\n font-size: 16px;\n color: #333;\n}
图标字体本质上还是文字,可以使用 style 和 className 设置图标的大小和颜色。
\n","order":"3"},"codes":{"jsx":"import { Icon } from '@alifd/next';\n\nReactDOM.render(\nimport { Icon } from '@alifd/next';\n\nReactDOM.render(\n <div>\n <div className=\"icon-style-demo\">\n <Icon type=\"success\" style={{ color: '#1DC11D', marginRight: '10px' }} />\n This is a success message!\n </div>\n <div className=\"icon-style-demo\">\n <Icon type=\"warning\" style={{ color: '#FFA003', marginRight: '10px' }} />\n This is a warning message!\n </div>\n <div className=\"icon-style-demo\">\n <Icon type=\"error\" style={{ color: '#FF3333', marginRight: '10px' }} />\n This is a failure message!\n </div>\n </div>\n , mountNode);
.icon-style-demo {\n height: 24px;\n line-height: 24px;\n margin-bottom: 10px;\n font-size: 16px;\n color: #333;\n}
Click on the icon to copy the code.
\n","order":"1"},"codes":{"jsx":"import { Message, Icon } from '@alifd/next';\n\n\nimport CopyToClipboard from 'react-copy-to-clipboard';\n\nconst types = [\n 'smile', 'cry', 'success', 'warning', 'prompt',\n 'error', 'help', 'clock', 'success-filling', 'delete-filling',\n 'favorites-filling', 'add', 'minus', 'arrow-up', 'arrow-down',\n 'arrow-left', 'arrow-right', 'arrow-double-left', 'arrow-double-right', 'switch',\n 'sorting', 'descending', 'ascending', 'select', 'semi-select',\n 'loading', 'search', 'close', 'ellipsis', 'picture',\n 'calendar', 'ashbin', 'upload', 'download', 'set',\n 'edit', 'refresh', 'filter', 'attachment', 'account',\n 'email', 'atm', 'copy', 'exit', 'eye', 'eye-close', 'toggle-left', 'toggle-right',\n 'lock', 'unlock','chart-pie', 'chart-bar'\n];\n\n\nlet customTypes = [];\n\n// The code here is for fusion dev display custom Icon components only\nif (window.customIcons) {\n customTypes = window.customIcons;\n}\n\nconst handleCopy = () => Message.success('Copied!');\n\nReactDOM.render(\nimport { Message, Icon } from '@alifd/next';\n\n\nimport CopyToClipboard from 'react-copy-to-clipboard';\n\nconst types = [\n 'smile', 'cry', 'success', 'warning', 'prompt',\n 'error', 'help', 'clock', 'success-filling', 'delete-filling',\n 'favorites-filling', 'add', 'minus', 'arrow-up', 'arrow-down',\n 'arrow-left', 'arrow-right', 'arrow-double-left', 'arrow-double-right', 'switch',\n 'sorting', 'descending', 'ascending', 'select', 'semi-select',\n 'loading', 'search', 'close', 'ellipsis', 'picture',\n 'calendar', 'ashbin', 'upload', 'download', 'set',\n 'edit', 'refresh', 'filter', 'attachment', 'account',\n 'email', 'atm', 'copy', 'exit', 'eye', 'eye-close', 'toggle-left', 'toggle-right',\n 'lock', 'unlock','chart-pie', 'chart-bar'\n];\n\n\nlet customTypes = [];\n\n// The code here is for fusion dev display custom Icon components only\nif (window.customIcons) {\n customTypes = window.customIcons;\n}\n\nconst handleCopy = () => Message.success('Copied!');\n\nReactDOM.render(\n <div>\n <div className=\"icon-list-title\">Click on the icon to copy the code.</div>\n <ul className=\"icon-list\">\n {types.map((type, index) => (\n <CopyToClipboard key={index} text={`<Icon type=\"${type}\" />`} onCopy={handleCopy}>\n <li>\n <Icon type={type} size=\"xl\" />\n <span>{type}</span>\n </li>\n </CopyToClipboard>))}\n </ul>\n {\n customTypes.length ?\n <div>\n <div className=\"icon-list-custom-title\">Custom Icon</div>\n <ul className=\"icon-list\">\n {\n customTypes.map((type, index) => (\n <CopyToClipboard key={index} text={`<Icon type=\"${type}\" />`} onCopy={handleCopy}>\n <li>\n <Icon type={type} size=\"xl\" />\n <span>{type}</span>\n </li>\n </CopyToClipboard>))\n }\n </ul>\n </div> :\n null\n }\n\n </div>\n , mountNode);
.icon-list-title {\n margin-bottom: 20px;\n font-size: 24px;\n color: #333;\n}\n\n.icon-list {\n margin: 0;\n padding: 0;\n list-style: none;\n}\n\n.icon-list li {\n display: inline-block;\n width: 140px;\n padding: 30px 0;\n color: #666;\n cursor: pointer;\n}\n\n.icon-list li:hover {\n color: #333;\n background-color: #f7f7f7;\n}\n\n.icon-list i {\n display: block;\n width: 32px;\n margin: 0 auto;\n}\n\n.icon-list span {\n display: block;\n margin-top: 10px;\n text-align: center;\n font-size: 14px;\n}\n\n.icon-list-custom-title {\n margin: 20px 0 20px 10px;\n font-size: 20px;\n color: #333;\n}
点击图标复制代码。
\n","order":"1"},"codes":{"jsx":"import { Message, Icon } from '@alifd/next';\n\n\nimport CopyToClipboard from 'react-copy-to-clipboard';\n\nconst types = [\n 'smile', 'cry', 'success', 'warning', 'prompt',\n 'error', 'help', 'clock', 'success-filling', 'delete-filling',\n 'favorites-filling', 'add', 'minus', 'arrow-up', 'arrow-down',\n 'arrow-left', 'arrow-right', 'arrow-double-left', 'arrow-double-right', 'switch',\n 'sorting', 'descending', 'ascending', 'select', 'semi-select',\n 'loading', 'search', 'close', 'ellipsis', 'picture',\n 'calendar', 'ashbin', 'upload', 'download', 'set',\n 'edit', 'refresh', 'filter', 'attachment', 'account',\n 'email', 'atm', 'copy', 'exit', 'eye', 'eye-close', 'toggle-left', 'toggle-right',\n 'lock', 'unlock','chart-pie', 'chart-bar'\n];\n\n\nlet customTypes = [];\n\n// The code here is for fusion dev display custom Icon components only\nif (window.customIcons) {\n customTypes = window.customIcons;\n}\n\nconst handleCopy = () => Message.success('Copied!');\n\nReactDOM.render(\nimport { Message, Icon } from '@alifd/next';\n\n\nimport CopyToClipboard from 'react-copy-to-clipboard';\n\nconst types = [\n 'smile', 'cry', 'success', 'warning', 'prompt',\n 'error', 'help', 'clock', 'success-filling', 'delete-filling',\n 'favorites-filling', 'add', 'minus', 'arrow-up', 'arrow-down',\n 'arrow-left', 'arrow-right', 'arrow-double-left', 'arrow-double-right', 'switch',\n 'sorting', 'descending', 'ascending', 'select', 'semi-select',\n 'loading', 'search', 'close', 'ellipsis', 'picture',\n 'calendar', 'ashbin', 'upload', 'download', 'set',\n 'edit', 'refresh', 'filter', 'attachment', 'account',\n 'email', 'atm', 'copy', 'exit', 'eye', 'eye-close', 'toggle-left', 'toggle-right',\n 'lock', 'unlock','chart-pie', 'chart-bar'\n];\n\n\nlet customTypes = [];\n\n// The code here is for fusion dev display custom Icon components only\nif (window.customIcons) {\n customTypes = window.customIcons;\n}\n\nconst handleCopy = () => Message.success('Copied!');\n\nReactDOM.render(\n <div>\n <div className=\"icon-list-title\">Click on the icon to copy the code.</div>\n <ul className=\"icon-list\">\n {types.map((type, index) => (\n <CopyToClipboard key={index} text={`<Icon type=\"${type}\" />`} onCopy={handleCopy}>\n <li>\n <Icon type={type} size=\"xl\" />\n <span>{type}</span>\n </li>\n </CopyToClipboard>))}\n </ul>\n {\n customTypes.length ?\n <div>\n <div className=\"icon-list-custom-title\">Custom Icon</div>\n <ul className=\"icon-list\">\n {\n customTypes.map((type, index) => (\n <CopyToClipboard key={index} text={`<Icon type=\"${type}\" />`} onCopy={handleCopy}>\n <li>\n <Icon type={type} size=\"xl\" />\n <span>{type}</span>\n </li>\n </CopyToClipboard>))\n }\n </ul>\n </div> :\n null\n }\n\n </div>\n , mountNode);
.icon-list-title {\n margin-bottom: 20px;\n font-size: 24px;\n color: #333;\n}\n\n.icon-list {\n margin: 0;\n padding: 0;\n list-style: none;\n}\n\n.icon-list li {\n display: inline-block;\n width: 140px;\n padding: 30px 0;\n color: #666;\n cursor: pointer;\n}\n\n.icon-list li:hover {\n color: #333;\n background-color: #f7f7f7;\n}\n\n.icon-list i {\n display: block;\n width: 32px;\n margin: 0 auto;\n}\n\n.icon-list span {\n display: block;\n margin-top: 10px;\n text-align: center;\n font-size: 14px;\n}\n\n.icon-list-custom-title {\n margin: 20px 0 20px 10px;\n font-size: 20px;\n color: #333;\n}
Param | \nDescripiton | \nType | \nDefault Value | \n
---|---|---|---|
size | \nTo set the icon size option: 'xxs', 'xs', 'small', 'medium', 'large', 'xl', 'xxl', 'xxxl', 'inherit' | \nEnum | \n'medium' | \n
type | \nSpecify which icon to display | \nString | \n- | \n
aria-hidden
忽略;若为按钮类型icon,请务必设置 role="button"
和 aria-label
参数 | \n说明 | \n类型 | \n默认值 | \n
---|---|---|---|
size | \n指定图标大小 可选值: 'xxs', 'xs', 'small', 'medium', 'large', 'xl', 'xxl', 'xxxl', 'inherit' | \nEnum | \n'medium' | \n
type | \n指定显示哪种图标 | \nString | \n- | \n
Describe the Input
component by aria-label
.Please refer to ARIA and KeyBoard
for keyboard operation.
import { Input } from '@alifd/next';\n\nfunction onChange(v) {\n console.log(v);\n}\nfunction onKeyDown(v) {\n console.log(v);\n}\nReactDOM.render(<div>\n <Input size=\"large\" placeholder=\"please input\" onChange={onChange} onKeyDown={onKeyDown} aria-label=\"this is input\" /> \n</div>\n , mountNode);
通过aria-label
对Input
组件进行描述。关于键盘操作请参考ARIA and KeyBoard
。
import { Input } from '@alifd/next';\n\nfunction onChange(v) {\n console.log(v);\n}\nfunction onKeyDown(v) {\n console.log(v);\n}\nReactDOM.render(<div>\n <Input size=\"large\" placeholder=\"please input\" onChange={onChange} onKeyDown={onKeyDown} aria-label=\"this is input\" /> \n</div>\n , mountNode);
import { Input } from '@alifd/next';\n\nReactDOM.render(<div>\n <Input hasLimitHint\n addonTextBefore=\"http://\"\n addonTextAfter=\".com\"\n size=\"large\"\n defaultValue=\"alibaba\"\n maxLength={2}\n aria-label=\"input with config of addonTextBefore and addonTextAfter\" /><br /><br />\n\n <Input\n addonTextBefore=\"http://\"\n addonTextAfter=\".com\"\n size=\"medium\"\n value=\"alibaba\"\n aria-label=\"input with config of addonTextBefore and addonTextAfter\" /><br /><br />\n\n <Input\n addonTextBefore=\"http://\"\n addonTextAfter=\".com\"\n size=\"small\"\n value=\"alibaba\"\n aria-label=\"input with config of addonTextBefore and addonTextAfter\" />\n</div>\n , mountNode);
import { Input } from '@alifd/next';\n\nReactDOM.render(<div>\n <Input hasLimitHint\n addonTextBefore=\"http://\"\n addonTextAfter=\".com\"\n size=\"large\"\n defaultValue=\"alibaba\"\n maxLength={2}\n aria-label=\"input with config of addonTextBefore and addonTextAfter\" /><br /><br />\n\n <Input\n addonTextBefore=\"http://\"\n addonTextAfter=\".com\"\n size=\"medium\"\n value=\"alibaba\"\n aria-label=\"input with config of addonTextBefore and addonTextAfter\" /><br /><br />\n\n <Input\n addonTextBefore=\"http://\"\n addonTextAfter=\".com\"\n size=\"small\"\n value=\"alibaba\"\n aria-label=\"input with config of addonTextBefore and addonTextAfter\" />\n</div>\n , mountNode);
Set Input
as a TextArea
import { Input } from '@alifd/next';\n\n\n\n\nReactDOM.render(\n <div >\n <Input.TextArea\n autoHeight\n trim\n aria-label=\"auto height\"\n placeholder=\"autoHeight\"\n onKeyDown={(e, opts) => {\n console.log('onKeyDown', opts);\n }} /><br/><br/>\n\n <Input.TextArea aria-label=\"auto height\" autoHeight={{ minRows: 2, maxRows: 6 }} />\n </div>\n , mountNode);
设置 Input
为 多行文本域;
import { Input } from '@alifd/next';\n\n\n\n\nReactDOM.render(\n <div >\n <Input.TextArea\n autoHeight\n trim\n aria-label=\"auto height\"\n placeholder=\"autoHeight\"\n onKeyDown={(e, opts) => {\n console.log('onKeyDown', opts);\n }} /><br/><br/>\n\n <Input.TextArea aria-label=\"auto height\" autoHeight={{ minRows: 2, maxRows: 6 }} />\n </div>\n , mountNode);
import { Input } from '@alifd/next';\n\nfunction onChange(v) {\n console.log(v);\n}\n\nReactDOM.render(<div>\n <Input size=\"large\" placeholder=\"Large\" onChange={onChange} aria-label=\"Large\" /><br /><br />\n\n <span id=\"J_InputMedium\" style={{display: 'none'}}>Aria Labelby Demo </span>\n <Input placeholder=\"Medium\" aria-label=\"Medium\" aria-labelledby=\"J_InputMedium\" /><br /><br />\n\n <Input placeholder=\"Small\" size=\"small\" label=\"SIZE :\" id=\"J_InputSmall\" /><br /><br />\n\n <Input.TextArea placeholder=\"TextArea\" aria-label=\"TextArea\" />\n</div>, mountNode);
import { Input } from '@alifd/next';\n\nfunction onChange(v) {\n console.log(v);\n}\n\nReactDOM.render(<div>\n <Input size=\"large\" placeholder=\"Large\" onChange={onChange} aria-label=\"Large\" /><br /><br />\n\n <span id=\"J_InputMedium\" style={{display: 'none'}}>Aria Labelby Demo </span>\n <Input placeholder=\"Medium\" aria-label=\"Medium\" aria-labelledby=\"J_InputMedium\" /><br /><br />\n\n <Input placeholder=\"Small\" size=\"small\" label=\"SIZE :\" id=\"J_InputSmall\" /><br /><br />\n\n <Input.TextArea placeholder=\"TextArea\" aria-label=\"TextArea\" />\n</div>, mountNode);
import { Input } from '@alifd/next';\n\nconst onChange = (value) => {\n console.log(value);\n};\nconst onBlur = (e) => {\n console.log(e);\n};\n\nReactDOM.render(\n <div>\n <Input\n hasClear\n defaultValue=\"clear by click\"\n size=\"small\"\n aria-label=\"input with config of hasClear\" onChange={onChange} /><br/><br/>\n\n <Input\n hasClear\n defaultValue=\"2019-09-10 10:10:20\"\n aria-label=\"input with config of hasClear\"\n onChange={onChange}\n onBlur={onBlur}\n hint=\"calendar\"/><br/><br/>\n\n <Input\n hasClear\n defaultValue=\"clear by click\"\n size=\"large\"\n aria-label=\"input with config of hasClear\"\n onChange={onChange} /><br/><br/>\n </div>\n , mountNode);
通过设置 hasClear 添加清除按钮.
\nhint为水印按钮,和hasClear占用同一个地方配合使用
\n","order":"3"},"codes":{"jsx":"import { Input } from '@alifd/next';\n\nconst onChange = (value) => {\n console.log(value);\n};\nconst onBlur = (e) => {\n console.log(e);\n};\n\nReactDOM.render(\nimport { Input } from '@alifd/next';\n\nconst onChange = (value) => {\n console.log(value);\n};\nconst onBlur = (e) => {\n console.log(e);\n};\n\nReactDOM.render(\n <div>\n <Input\n hasClear\n defaultValue=\"clear by click\"\n size=\"small\"\n aria-label=\"input with config of hasClear\" onChange={onChange} /><br/><br/>\n\n <Input\n hasClear\n defaultValue=\"2019-09-10 10:10:20\"\n aria-label=\"input with config of hasClear\"\n onChange={onChange}\n onBlur={onBlur}\n hint=\"calendar\"/><br/><br/>\n\n <Input\n hasClear\n defaultValue=\"clear by click\"\n size=\"large\"\n aria-label=\"input with config of hasClear\"\n onChange={onChange} /><br/><br/>\n </div>\n , mountNode);
Set Input
as disabled
state
import { Input } from '@alifd/next';\n\nReactDOM.render(\n <div>\n <Input disabled aria-label=\"disabled\" placeholder=\"disabled\" size=\"small\"/><br /><br />\n\n <Input\n disabled\n aria-label=\"disabled\"\n addonTextBefore=\"http://\"\n addonTextAfter=\".com\"\n size=\"medium\"\n value=\"alibaba\"/><br /><br />\n\n <Input disabled aria-label=\"disabled\" placeholder=\"medium\" maxLength={10} hasLimitHint/><br /><br />\n\n <Input.TextArea disabled aria-label=\"disabled\" placeholder=\"medium\" maxLength={10} hasLimitHint/>\n </div>\n , mountNode);
为 Input
设置 disabled
状态;
import { Input } from '@alifd/next';\n\nReactDOM.render(\n <div>\n <Input disabled aria-label=\"disabled\" placeholder=\"disabled\" size=\"small\"/><br /><br />\n\n <Input\n disabled\n aria-label=\"disabled\"\n addonTextBefore=\"http://\"\n addonTextAfter=\".com\"\n size=\"medium\"\n value=\"alibaba\"/><br /><br />\n\n <Input disabled aria-label=\"disabled\" placeholder=\"medium\" maxLength={10} hasLimitHint/><br /><br />\n\n <Input.TextArea disabled aria-label=\"disabled\" placeholder=\"medium\" maxLength={10} hasLimitHint/>\n </div>\n , mountNode);
Group has an ability that total lenght is definite and its inner input is flexible.
\n","order":"11"},"codes":{"jsx":"import { Input, Select, Button } from '@alifd/next';\n\n\nconst select = ();\nconst button = ();\n\nReactDOM.render(import { Input, Select, Button } from '@alifd/next';\n\n\nconst select = (<Select aria-label=\"please select\" >\n <option value=\"https\">https</option>\n <option value=\"http\">http</option>\n</Select>);\nconst button = (<Button>search</Button>);\n\nReactDOM.render(<div>\n <Input.Group addonBefore={select} addonAfter={button}>\n <Input hasClear defaultValue=\"abc\" style={{width: '100%'}} aria-label=\"please input\" />\n </Input.Group>\n <br/><br/>\n <Input addonTextAfter=\".com\" addonBefore={select} aria-label=\"please input\" />\n</div>, mountNode);
Group 具有两边长度固定中间组件任意伸缩的能力。在Input中可以用addonBefore/addonAfter快速使用
\n","order":"11"},"codes":{"jsx":"import { Input, Select, Button } from '@alifd/next';\n\n\nconst select = ();\nconst button = ();\n\nReactDOM.render(import { Input, Select, Button } from '@alifd/next';\n\n\nconst select = (<Select aria-label=\"please select\" >\n <option value=\"https\">https</option>\n <option value=\"http\">http</option>\n</Select>);\nconst button = (<Button>search</Button>);\n\nReactDOM.render(<div>\n <Input.Group addonBefore={select} addonAfter={button}>\n <Input hasClear defaultValue=\"abc\" style={{width: '100%'}} aria-label=\"please input\" />\n </Input.Group>\n <br/><br/>\n <Input addonTextAfter=\".com\" addonBefore={select} aria-label=\"please input\" />\n</div>, mountNode);
Add Watermark/Prefix/Suffix for Input
\n","order":"8"},"codes":{"jsx":"import { Input, Icon } from '@alifd/next';\n\n\nclass App extends React.Component {\n state = {\n v: ''\n };\n\n onChange = (v) => {\n this.setState({\n v\n });\n };\n\n onClick = () => {\n console.log(this.state.v);\n };\n\n render() {\n\n return (import { Input, Icon } from '@alifd/next';\n\n\nclass App extends React.Component {\n state = {\n v: ''\n };\n\n onChange = (v) => {\n this.setState({\n v\n });\n };\n\n onClick = () => {\n console.log(this.state.v);\n };\n\n render() {\n\n return (<div>\n <Input\n innerBefore={<Icon type=\"search\" style={{margin: 4}} onClick={this.onClick} />}\n placeholder=\"search\"\n value={this.state.v}\n aria-label=\"input with config of innerBefore\"\n onChange={this.onChange}\n /><br /><br />\n\n <Input\n innerAfter={<Icon type=\"search\" size=\"xs\" onClick={this.onClick} style={{margin: 4}}/>}\n placeholder=\"search\"\n value={this.state.v}\n aria-label=\"input with config of innerAfter\"\n onChange={this.onChange}\n /><br /><br />\n\n <Input\n disabled\n defaultValue=\"hi\"\n innerAfter={<Icon type=\"calendar\" style={{margin: 4}}/>}\n aria-label=\"input with config of innerAfter and disabled\" />\n </div>);\n }\n}\n\nReactDOM.render(<App/>, mountNode);
可以添加水印, 为input前后端增加额外内容
\n","order":"8"},"codes":{"jsx":"import { Input, Icon } from '@alifd/next';\n\n\nclass App extends React.Component {\n state = {\n v: ''\n };\n\n onChange = (v) => {\n this.setState({\n v\n });\n };\n\n onClick = () => {\n console.log(this.state.v);\n };\n\n render() {\n\n return (import { Input, Icon } from '@alifd/next';\n\n\nclass App extends React.Component {\n state = {\n v: ''\n };\n\n onChange = (v) => {\n this.setState({\n v\n });\n };\n\n onClick = () => {\n console.log(this.state.v);\n };\n\n render() {\n\n return (<div>\n <Input\n innerBefore={<Icon type=\"search\" style={{margin: 4}} onClick={this.onClick} />}\n placeholder=\"search\"\n value={this.state.v}\n aria-label=\"input with config of innerBefore\"\n onChange={this.onChange}\n /><br /><br />\n\n <Input\n innerAfter={<Icon type=\"search\" size=\"xs\" onClick={this.onClick} style={{margin: 4}}/>}\n placeholder=\"search\"\n value={this.state.v}\n aria-label=\"input with config of innerAfter\"\n onChange={this.onChange}\n /><br /><br />\n\n <Input\n disabled\n defaultValue=\"hi\"\n innerAfter={<Icon type=\"calendar\" style={{margin: 4}}/>}\n aria-label=\"input with config of innerAfter and disabled\" />\n </div>);\n }\n}\n\nReactDOM.render(<App/>, mountNode);
the prop hasLimitHint
will limit the number of characters
import { Input } from '@alifd/next';\n\nclass App extends React.Component {\n constructor(props) {\n super(props);\n this.state = {\n maxLength: 10,\n control: 'maxLen control'\n };\n }\n\n onChange(v) {\n console.log(v);\n this.setState({\n control: v\n });\n }\n\n onKeyDown(e, opts) {\n console.log('onKeyDown', opts);\n }\n\n render() {\n return (<div>\n <Input\n maxLength={10}\n size=\"large\"\n placeholder=\"Large\"\n value={this.state.control}\n hasLimitHint\n aria-label=\"input max length 10\"\n onChange={this.onChange.bind(this)}\n onKeyDown={this.onKeyDown.bind(this)} /><br /><br />\n\n <Input\n maxLength={20}\n placeholder=\"medium\"\n hasLimitHint\n cutString={false}\n aria-label=\"input max length 20\"\n onChange={(v) => {\n this.setState({control: v});\n console.log(v);\n }}\n onKeyDown={(e, opts) => {\n console.log('onKeyDown', opts);\n }} /><br /><br />\n\n <Input\n hasLimitHint\n size=\"small\"\n placeholder=\"small\"\n maxLength={100}\n aria-label=\"input max length 100\" /><br /><br />\n\n <Input.TextArea\n placeholder=\"TextArea\"\n maxLength={100}\n rows={4}\n hasLimitHint\n aria-label=\"input max length 100\" /><br /><br />\n\n <Input maxLength={5} placeholder=\"Original maxLength\" aria-label=\"input max length 5\" />\n </div>);\n }\n}\n\nReactDOM.render(<App/>, mountNode);
最大长度 hasLimitHint 会展现限制数字; cutString 可控制是否要切割字符串, 用于只展示最大长度
\n","order":"5"},"codes":{"jsx":"import { Input } from '@alifd/next';\n\nclass App extends React.Component {\n constructor(props) {\n super(props);\n this.state = {\n maxLength: 10,\n control: 'maxLen control'\n };\n }\n\n onChange(v) {\n console.log(v);\n this.setState({\n control: v\n });\n }\n\n onKeyDown(e, opts) {\n console.log('onKeyDown', opts);\n }\n\n render() {\n return (import { Input } from '@alifd/next';\n\nclass App extends React.Component {\n constructor(props) {\n super(props);\n this.state = {\n maxLength: 10,\n control: 'maxLen control'\n };\n }\n\n onChange(v) {\n console.log(v);\n this.setState({\n control: v\n });\n }\n\n onKeyDown(e, opts) {\n console.log('onKeyDown', opts);\n }\n\n render() {\n return (<div>\n <Input\n maxLength={10}\n size=\"large\"\n placeholder=\"Large\"\n value={this.state.control}\n hasLimitHint\n aria-label=\"input max length 10\"\n onChange={this.onChange.bind(this)}\n onKeyDown={this.onKeyDown.bind(this)} /><br /><br />\n\n <Input\n maxLength={20}\n placeholder=\"medium\"\n hasLimitHint\n cutString={false}\n aria-label=\"input max length 20\"\n onChange={(v) => {\n this.setState({control: v});\n console.log(v);\n }}\n onKeyDown={(e, opts) => {\n console.log('onKeyDown', opts);\n }} /><br /><br />\n\n <Input\n hasLimitHint\n size=\"small\"\n placeholder=\"small\"\n maxLength={100}\n aria-label=\"input max length 100\" /><br /><br />\n\n <Input.TextArea\n placeholder=\"TextArea\"\n maxLength={100}\n rows={4}\n hasLimitHint\n aria-label=\"input max length 100\" /><br /><br />\n\n <Input maxLength={5} placeholder=\"Original maxLength\" aria-label=\"input max length 5\" />\n </div>);\n }\n}\n\nReactDOM.render(<App/>, mountNode);
Set Input
as a password type input;
import { Input } from '@alifd/next';\n\nfunction onChange(v) {\n console.log(v);\n}\n\nReactDOM.render(\n <div>\n <Input.Password placeholder=\"please input password\" onChange={onChange} /><br /><br />\n <Input.Password size=\"large\" placeholder=\"please input password\" onChange={onChange} /><br /><br />\n <Input.Password size=\"small\" placeholder=\"please input password\" onChange={onChange} /><br /><br />\n </div>\n , mountNode);
设置 Input
为 密码类型;
import { Input } from '@alifd/next';\n\nfunction onChange(v) {\n console.log(v);\n}\n\nReactDOM.render(\n <div>\n <Input.Password placeholder=\"please input password\" onChange={onChange} /><br /><br />\n <Input.Password size=\"large\" placeholder=\"please input password\" onChange={onChange} /><br /><br />\n <Input.Password size=\"small\" placeholder=\"please input password\" onChange={onChange} /><br /><br />\n </div>\n , mountNode);
Set Error State for Input
\n","order":"4"},"codes":{"jsx":"import { Input } from '@alifd/next';\n\nReactDOM.render(\nimport { Input } from '@alifd/next';\n\nReactDOM.render(\n <div>\n <Input state=\"error\"\n placeholder=\"error\"\n size=\"small\"\n aria-live=\"assertive\"\n aria-label=\"error\" /><br/><br/>\n <Input state=\"error\"\n hasLimitHint\n maxLength={100}\n placeholder=\"error\"\n size=\"medium\"\n aria-live=\"assertive\"\n aria-label=\"error\" /><br/><br/>\n <Input state=\"error\"\n multiple\n placeholder=\"error\"\n size=\"large\"\n aria-live=\"assertive\"\n aria-label=\"error\" /><br/><br/>\n\n <Input state=\"success\"\n size=\"small\"\n value=\"success\"\n aria-live=\"assertive\"\n aria-label=\"success\"/><br/><br/>\n <Input state=\"success\"\n maxLength={100}\n hasLimitHint\n placeholder=\"success\"\n size=\"medium\"\n aria-live=\"assertive\"\n aria-label=\"success\"/><br/><br/>\n <Input state=\"success\"\n placeholder=\"success\"\n size=\"large\"\n aria-live=\"assertive\"\n aria-label=\"success\"/><br/><br/>\n\n <Input state=\"loading\"\n placeholder=\"loading\"\n size=\"small\"\n aria-live=\"assertive\"\n aria-label=\"loading\"/><br/><br/>\n <Input state=\"loading\"\n placeholder=\"loading\"\n size=\"medium\"\n aria-live=\"assertive\"\n aria-label=\"loading\"/><br/><br/>\n <Input state=\"loading\"\n placeholder=\"loading\"\n size=\"large\"\n aria-live=\"assertive\"\n aria-label=\"loading\"/><br/><br/>\n </div>\n , mountNode);
为 Input
设置 error
状态;
import { Input } from '@alifd/next';\n\nReactDOM.render(\n <div>\n <Input state=\"error\"\n placeholder=\"error\"\n size=\"small\"\n aria-live=\"assertive\"\n aria-label=\"error\" /><br/><br/>\n <Input state=\"error\"\n hasLimitHint\n maxLength={100}\n placeholder=\"error\"\n size=\"medium\"\n aria-live=\"assertive\"\n aria-label=\"error\" /><br/><br/>\n <Input state=\"error\"\n multiple\n placeholder=\"error\"\n size=\"large\"\n aria-live=\"assertive\"\n aria-label=\"error\" /><br/><br/>\n\n <Input state=\"success\"\n size=\"small\"\n value=\"success\"\n aria-live=\"assertive\"\n aria-label=\"success\"/><br/><br/>\n <Input state=\"success\"\n maxLength={100}\n hasLimitHint\n placeholder=\"success\"\n size=\"medium\"\n aria-live=\"assertive\"\n aria-label=\"success\"/><br/><br/>\n <Input state=\"success\"\n placeholder=\"success\"\n size=\"large\"\n aria-live=\"assertive\"\n aria-label=\"success\"/><br/><br/>\n\n <Input state=\"loading\"\n placeholder=\"loading\"\n size=\"small\"\n aria-live=\"assertive\"\n aria-label=\"loading\"/><br/><br/>\n <Input state=\"loading\"\n placeholder=\"loading\"\n size=\"medium\"\n aria-live=\"assertive\"\n aria-label=\"loading\"/><br/><br/>\n <Input state=\"loading\"\n placeholder=\"loading\"\n size=\"large\"\n aria-live=\"assertive\"\n aria-label=\"loading\"/><br/><br/>\n </div>\n , mountNode);
Custom style can be set using param style
.
import { Input } from '@alifd/next';\n\nReactDOM.render(\n <div>\n <Input placeholder=\"width:400\" style={{width: 400}} aria-label=\"style width 400\" /><br/><br/>\n\n <Input\n addonTextBefore=\"http://\"\n addonTextAfter=\".com\"\n size=\"medium\"\n value=\"alibaba\"\n style={{width: 400}} aria-label=\"style width 400\" /><br/><br/>\n\n <Input\n placeholder=\"medium\"\n maxLength={10}\n hasLimitHint\n style={{width: 400}} aria-label=\"style width 400\" /><br/><br/>\n\n <Input\n placeholder=\"medium\"\n hasClear maxLength={10}\n hasLimitHint style={{width: 400}}\n className=\"my-input-class\"\n state=\"success\"\n aria-label=\"style width 400\" /><br/><br/>\n\n <Input placeholder=\"className\" className=\"my-input-class\" aria-label=\"custom my input class\" />\n <Input htmlType=\"hidden\" aria-label=\"hidden input\" />\n </div>\n , mountNode);
body .my-input-class {\n width:500px;\n}
通过style设置宽度
\n","order":"12"},"codes":{"jsx":"import { Input } from '@alifd/next';\n\nReactDOM.render(\nimport { Input } from '@alifd/next';\n\nReactDOM.render(\n <div>\n <Input placeholder=\"width:400\" style={{width: 400}} aria-label=\"style width 400\" /><br/><br/>\n\n <Input\n addonTextBefore=\"http://\"\n addonTextAfter=\".com\"\n size=\"medium\"\n value=\"alibaba\"\n style={{width: 400}} aria-label=\"style width 400\" /><br/><br/>\n\n <Input\n placeholder=\"medium\"\n maxLength={10}\n hasLimitHint\n style={{width: 400}} aria-label=\"style width 400\" /><br/><br/>\n\n <Input\n placeholder=\"medium\"\n hasClear maxLength={10}\n hasLimitHint style={{width: 400}}\n className=\"my-input-class\"\n state=\"success\"\n aria-label=\"style width 400\" /><br/><br/>\n\n <Input placeholder=\"className\" className=\"my-input-class\" aria-label=\"custom my input class\" />\n <Input htmlType=\"hidden\" aria-label=\"hidden input\" />\n </div>\n , mountNode);
body .my-input-class {\n width:500px;\n}
onChange callback will return the trimmed text value
\n","order":"6"},"codes":{"jsx":"import { Input } from '@alifd/next';\n\nclass App extends React.Component {\n state = {\n value: ''\n }\n\n onChange(value) {\n console.log('onChange', value);\n this.setState({\n value\n });\n }\n\n onKeyDown(e, opts) {\n console.log('onKeyDown', opts);\n }\n\n render() {\n return (import { Input } from '@alifd/next';\n\nclass App extends React.Component {\n state = {\n value: ''\n }\n\n onChange(value) {\n console.log('onChange', value);\n this.setState({\n value\n });\n }\n\n onKeyDown(e, opts) {\n console.log('onKeyDown', opts);\n }\n\n render() {\n return (<div>\n <Input trim placeholder=\"cant not input space\" aria-label=\"cant not input space\"\n onChange={this.onChange.bind(this)}\n onKeyDown={this.onKeyDown.bind(this)} />\n </div>);\n }\n}\nReactDOM.render(<App/>, mountNode);
onChange返回会自动去除头尾空字符
\n","order":"6"},"codes":{"jsx":"import { Input } from '@alifd/next';\n\nclass App extends React.Component {\n state = {\n value: ''\n }\n\n onChange(value) {\n console.log('onChange', value);\n this.setState({\n value\n });\n }\n\n onKeyDown(e, opts) {\n console.log('onKeyDown', opts);\n }\n\n render() {\n return (import { Input } from '@alifd/next';\n\nclass App extends React.Component {\n state = {\n value: ''\n }\n\n onChange(value) {\n console.log('onChange', value);\n this.setState({\n value\n });\n }\n\n onKeyDown(e, opts) {\n console.log('onKeyDown', opts);\n }\n\n render() {\n return (<div>\n <Input trim placeholder=\"cant not input space\" aria-label=\"cant not input space\"\n onChange={this.onChange.bind(this)}\n onKeyDown={this.onKeyDown.bind(this)} />\n </div>);\n }\n}\nReactDOM.render(<App/>, mountNode);
Form Input, use it with Form components usually.
\nParam | \nDescripiton | \nType | \nDefault Value | \n
---|---|---|---|
value | \ncurrent value | \nString/Number | \n- | \n
size | \nSize option: 'small' 'medium' 'large' | \nEnum | \n'medium' | \n
defaultValue | \ninital value | \nString/Number | \n- | \n
onChange | \ncallback when value changes signature: Function(value: String, e: Event) => void params: value: {String} data _e_: {Event} DOM Event Object | \nFunction | \nfunc.noop | \n
onKeyDown | \ncallback when on key down signature: Function(e: Event, opts: Object) => void params: _e_: {Event} DOM Event Object opts: {Object} extended information: - opts.overMaxLength: {Boolean} input has reached max length - opts.beTrimed: {Boolean} input whitespace has been trimed | \nFunction | \nfunc.noop | \n
disabled | \ndisabled state | \nBoolean | \nfalse | \n
maxLength | \nmax length | \nNumber | \nnull | \n
hasLimitHint | \nlimit max num of characters | \nBoolean | \nfalse | \n
cutString | \nwhen maxLength is set, auto cut string | \nBoolean | \ntrue | \n
readOnly | \nread only, forbid editing | \nBoolean | \nfalse | \n
trim | \nonChange will auto trim text | \nBoolean | \nfalse | \n
placeholder | \nplace holder | \nString | \n- | \n
onFocus | \ncallback when input get focused signature: Function(e: Event) => void params: _e_: {Event} DOM Event Object | \nFunction | \nfunc.noop | \n
onBlur | \ncallback when input lose focused signature: Function(e: Event) => void params: _e_: {Event} DOM Event Object | \nFunction | \nfunc.noop | \n
getValueLength | \ndefine the value length caculation signature: Function(value: String) => Number params: value: {String} Data returns: {Number} caculated length | \nFunction | \nfunc.noop | \n
htmlType | \nhtml input type | \nString | \n- | \n
state | \nstate option: 'error' 'loading' 'success' | \nEnum | \n- | \n
label | \nlabel | \nReactNode | \n- | \n
hasClear | \nclear button displays or not | \nBoolean | \n- | \n
hasBorder | \ninput border displays or not | \nBoolean | \ntrue | \n
onKeyDown | \ncallback when keyboard press down signature: Function() => void | \nFunction | \nfunc.noop | \n
onPressEnter | \ncallback when the enter key press down signature: Function() => void | \nFunction | \nfunc.noop | \n
hint | \nwatermark, a type of Icon, share a place with hasClear | \nString | \n- | \n
innerBefore | \nElements appended before text | \nReactNode | \n- | \n
innerAfter | \nElements appended after text | \nReactNode | \n- | \n
addonBefore | \nElements appended before input | \nReactNode | \n- | \n
addonAfter | \nElements appended after input | \nReactNode | \n- | \n
addonTextBefore | \ntext appended before input | \nReactNode | \n- | \n
addonTextAfter | \ntext appended before input | \nReactNode | \n- | \n
autoComplete | \nrequire browser support | \nString | \n'off' | \n
autoFocus | \nrequire browser support | \nBoolean | \n- | \n
Param | \nDescripiton | \nType | \nDefault Value | \n
---|---|---|---|
value | \ncurrentValue | \nString/Number | \n- | \n
defaultValue | \ninital value | \nString/Number | \n- | \n
onChange | \ncallback when value changes signature: Function(value: String, e: Event) => void params: value: {String} Data _e_: {Event} DOM Event | \nFunction | \nfunc.noop | \n
onKeyDown | \ncallback when on key down signature: Function(e: Event, opts: Object) => void params: _e_: {Event} DOM Event Object opts: {Object} extended information: - opts.overMaxLength: {Boolean} input has reached max length - opts.beTrimed: {Boolean} input whitespace has been trimed | \nFunction | \nfunc.noop | \n
disabled | \ndisabled state | \nBoolean | \nfalse | \n
maxLength | \nmax length | \nNumber | \nnull | \n
hasLimitHint | \nlimit max num of characters | \nBoolean | \nfalse | \n
cutString | \nwhen maxLength is set, auto cut string | \nBoolean | \ntrue | \n
readOnly | \nread only, forbid editing | \nBoolean | \nfalse | \n
trim | \nonChange will auto trim text | \nBoolean | \nfalse | \n
placeholder | \nplaceholder | \nString | \n- | \n
onFocus | \ncallback when input get focused signature: Function() => void | \nFunction | \nfunc.noop | \n
onBlur | \ncallback when input lose focused signature: Function() => void | \nFunction | \nfunc.noop | \n
getValueLength | \ndefine the value length caculation signature: Function(value: String) => Number params: value: {String} Data returns: {Number} caculated length | \nFunction | \nfunc.noop | \n
htmlType | \nhtml input type | \nString | \n- | \n
state | \nstate option: 'error' 'loading' 'success' | \nEnum | \n- | \n
autoHeight | \nheight auto fit, exapmle: true / {minRows: 2, maxRows: 4} | \nBoolean/Object | \nfalse | \n
rows | \nmultiline text height (Never use height to controll textarea's height for compatibility with IE9/10) | \nNumber | \n4 | \n
Param | \nDescripiton | \nType | \nDefault Value | \n
---|---|---|---|
addonBefore | \nElements appended before input | \nReactNode | \n- | \n
addonBeforeClassName | \nClassnames before input, usually use for css | \nString | \n- | \n
addonAfter | \nElements appended after input | \nReactNode | \n- | \n
addonAfterClassName | \nClassnames after input , usually use for css | \nString | \n- | \n
Param | \nDescripiton | \nType | \nDefault Value | \n
---|---|---|---|
getInputNode | \nget truely input html dom node | \nFunction | \n\n |
focus | \nget foucs signature: Function(start:Number, end: Number) params: start: {Number} cursor postion end: {Number} select end postion | \nFunction | \n
KeyBoard | \nDescripiton | \n
---|---|
Enter | \nTrigger the onKeyDown event | \n
Any | \nTrigger the onChange event | \n
表单输入,一般配合Form使用
\n参数 | \n说明 | \n类型 | \n默认值 | \n
---|---|---|---|
value | \n当前值 | \nString/Number | \n- | \n
size | \n尺寸 可选值: 'small'(小) 'medium'(中) 'large'(大) | \nEnum | \n'medium' | \n
defaultValue | \n初始化值 | \nString/Number | \n- | \n
onChange | \n发生改变的时候触发的回调 签名: Function(value: String, e: Event) => void 参数: value: {String} 数据 _e_: {Event} DOM事件对象 | \nFunction | \nfunc.noop | \n
onKeyDown | \n键盘按下的时候触发的回调 签名: Function(e: Event, opts: Object) => void 参数: _e_: {Event} DOM事件对象 opts: {Object} 可扩展的附加信息: - opts.overMaxLength: {Boolean} 已超出最大长度 - opts.beTrimed: {Boolean} 输入的空格被清理 | \nFunction | \nfunc.noop | \n
disabled | \n禁用状态 | \nBoolean | \nfalse | \n
maxLength | \n最大长度 | \nNumber | \nnull | \n
hasLimitHint | \n是否展现最大长度样式 | \nBoolean | \nfalse | \n
cutString | \n当设置了maxLength时,是否截断超出字符串 | \nBoolean | \ntrue | \n
readOnly | \n只读 | \nBoolean | \nfalse | \n
trim | \nonChange返回会自动去除头尾空字符 | \nBoolean | \nfalse | \n
placeholder | \n输入提示 | \nString | \n- | \n
onFocus | \n获取焦点时候触发的回调 签名: Function(e: Event) => void 参数: _e_: {Event} DOM事件对象 | \nFunction | \nfunc.noop | \n
onBlur | \n失去焦点时候触发的回调 签名: Function(e: Event) => void 参数: _e_: {Event} DOM事件对象 | \nFunction | \nfunc.noop | \n
getValueLength | \n自定义字符串计算长度方式 签名: Function(value: String) => Number 参数: value: {String} 数据 返回值: {Number} 自定义长度 | \nFunction | \nfunc.noop | \n
htmlType | \n原生type | \nString | \n- | \n
name | \nname | \nString | \n- | \n
state | \n状态 可选值: 'error'(错误) 'loading'(校验中) 'success'(成功) | \nEnum | \n- | \n
label | \nlabel | \nReactNode | \n- | \n
hasClear | \n是否出现clear按钮 | \nBoolean | \n- | \n
hasBorder | \n是否有边框 | \nBoolean | \ntrue | \n
onPressEnter | \n按下回车的回调 签名: Function() => void | \nFunction | \nfunc.noop | \n
hint | \n水印 (Icon的type类型,和hasClear占用一个地方) | \nString | \n- | \n
innerBefore | \n文字前附加内容 | \nReactNode | \n- | \n
innerAfter | \n文字后附加内容 | \nReactNode | \n- | \n
addonBefore | \n输入框前附加内容 | \nReactNode | \n- | \n
addonAfter | \n输入框后附加内容 | \nReactNode | \n- | \n
addonTextBefore | \n输入框前附加文字 | \nReactNode | \n- | \n
addonTextAfter | \n输入框后附加文字 | \nReactNode | \n- | \n
autoComplete | \n(原生input支持) | \nString | \n'off' | \n
autoFocus | \n自动聚焦(原生input支持) | \nBoolean | \n- | \n
参数 | \n说明 | \n类型 | \n默认值 | \n
---|---|---|---|
value | \n当前值 | \nString/Number | \n- | \n
defaultValue | \n初始化值 | \nString/Number | \n- | \n
onChange | \n发生改变的时候触发的回调 签名: Function(value: String, e: Event) => void 参数: value: {String} 数据 _e_: {Event} DOM事件对象 | \nFunction | \nfunc.noop | \n
onKeyDown | \n键盘按下的时候触发的回调 签名: Function(e: Event, opts: Object) => void 参数: _e_: {Event} DOM事件对象 opts: {Object} 可扩展的附加信息: - opts.overMaxLength: {Boolean} 已超出最大长度 - opts.beTrimed: {Boolean} 输入的空格被清理 | \nFunction | \nfunc.noop | \n
disabled | \n禁用状态 | \nBoolean | \nfalse | \n
maxLength | \n最大长度 | \nNumber | \nnull | \n
hasLimitHint | \n是否展现最大长度样式 | \nBoolean | \nfalse | \n
cutString | \n当设置了maxLength时,是否截断超出字符串 | \nBoolean | \ntrue | \n
readOnly | \n只读 | \nBoolean | \nfalse | \n
trim | \nonChange返回会自动去除头尾空字符 | \nBoolean | \nfalse | \n
placeholder | \n输入提示 | \nString | \n- | \n
onFocus | \n获取焦点时候触发的回调 签名: Function(e: Event) => void 参数: _e_: {Event} DOM事件对象 | \nFunction | \nfunc.noop | \n
onBlur | \n失去焦点时候触发的回调 签名: Function(e: Event) => void 参数: _e_: {Event} DOM事件对象 | \nFunction | \nfunc.noop | \n
getValueLength | \n自定义字符串计算长度方式 签名: Function(value: String) => Number 参数: value: {String} 数据 返回值: {Number} 自定义长度 | \nFunction | \nfunc.noop | \n
htmlType | \n原生type | \nString | \n- | \n
name | \nname | \nString | \n- | \n
state | \n状态 可选值: 'error'(错误) | \nEnum | \n- | \n
hasBorder | \n是否有边框 | \nBoolean | \ntrue | \n
autoHeight | \n自动高度 true / {minRows: 2, maxRows: 4} | \nBoolean/Object | \nfalse | \n
rows | \n多行文本框高度 (不要直接用height设置多行文本框的高度, ie9 10会有兼容性问题) | \nNumber | \n4 | \n
参数 | \n说明 | \n类型 | \n默认值 | \n
---|---|---|---|
addonBefore | \n输入框前附加内容 | \nReactNode | \n- | \n
addonBeforeClassName | \n输入框前附加内容css | \nString | \n- | \n
addonAfter | \n输入框后附加内容 | \nReactNode | \n- | \n
addonAfterClassName | \n输入框后额外css | \nString | \n- | \n
rtl | \nrtl | \nBoolean | \n- | \n
参数 | \n说明 | \n类型 | \n默认值 | \n
---|---|---|---|
getInputNode | \n获取真正input节点 | \nFunction | \n\n |
focus | \n获取焦点 签名: Function(start:Number, end: Number) 参数: start: {Number} 光标起始位置 end: {Number} 选择结束位置 | \nFunction | \n
按键 | \n说明 | \n
---|---|
Enter | \n触发onKeyDown事件 | \n
Any | \n触发onChange事件 | \n
a basic way to use it
\n","order":"0"},"codes":{"jsx":"import { Loading } from '@alifd/next';\n\nReactDOM.render(\nimport { Loading } from '@alifd/next';\n\nReactDOM.render(\n <div>\n <div>LTR\n <Loading tip=\"加载中...\" >\n <div className=\"demo\">test</div>\n </Loading>\n </div>\n <div>RTL\n <Loading tip=\"加载中...\" rtl >\n <div className=\"demo\">test</div>\n </Loading>\n </div>\n </div>\n , mountNode);
.demo {\n width: 500px;\n background-color: #F2F3F7;\n text-align: center;\n padding:50px;\n}
最简单的用法。
\n","order":"0"},"codes":{"jsx":"import { Loading } from '@alifd/next';\n\nReactDOM.render(\nimport { Loading } from '@alifd/next';\n\nReactDOM.render(\n <div>\n <div>LTR\n <Loading tip=\"加载中...\" >\n <div className=\"demo\">test</div>\n </Loading>\n </div>\n <div>RTL\n <Loading tip=\"加载中...\" rtl >\n <div className=\"demo\">test</div>\n </Loading>\n </div>\n </div>\n , mountNode);
.demo {\n width: 500px;\n background-color: #F2F3F7;\n text-align: center;\n padding:50px;\n}
display a fullscreen loading
\n","order":"3"},"codes":{"jsx":"import { Loading, Button } from '@alifd/next';\n\n\n\nclass App extends React.Component {\n\n constructor(props, context) {\n super(props, context);\n this.state = {\n visible: false\n };\n }\n\n onClick() {\n this.setState({visible: !this.state.visible});\n }\n\n onClose = () => {\n this.setState({\n visible: false\n });\n }\n\n render() {\n return (\n \nimport { Loading, Button } from '@alifd/next';\n\n\n\nclass App extends React.Component {\n\n constructor(props, context) {\n super(props, context);\n this.state = {\n visible: false\n };\n }\n\n onClick() {\n this.setState({visible: !this.state.visible});\n }\n\n onClose = () => {\n this.setState({\n visible: false\n });\n }\n\n render() {\n return (\n <span>\n <Loading visible={this.state.visible}\n fullScreen\n shape=\"fusion-reactor\"\n safeNode={this.btn}\n onVisibleChange={this.onClose.bind(this)}>\n <Button onClick={this.onClick.bind(this)} ref={ref => (this.btn = ref)}>Full Screen</Button>\n </Loading>\n </span>\n );\n }\n}\n\nReactDOM.render(<App/>, mountNode);
全屏展示
\n","order":"3"},"codes":{"jsx":"import { Loading, Button } from '@alifd/next';\n\n\n\nclass App extends React.Component {\n\n constructor(props, context) {\n super(props, context);\n this.state = {\n visible: false\n };\n }\n\n onClick() {\n this.setState({visible: !this.state.visible});\n }\n\n onClose = () => {\n this.setState({\n visible: false\n });\n }\n\n render() {\n return (\n \nimport { Loading, Button } from '@alifd/next';\n\n\n\nclass App extends React.Component {\n\n constructor(props, context) {\n super(props, context);\n this.state = {\n visible: false\n };\n }\n\n onClick() {\n this.setState({visible: !this.state.visible});\n }\n\n onClose = () => {\n this.setState({\n visible: false\n });\n }\n\n render() {\n return (\n <span>\n <Loading visible={this.state.visible}\n fullScreen\n shape=\"fusion-reactor\"\n safeNode={this.btn}\n onVisibleChange={this.onClose.bind(this)}>\n <Button onClick={this.onClick.bind(this)} ref={ref => (this.btn = ref)}>Full Screen</Button>\n </Loading>\n </span>\n );\n }\n}\n\nReactDOM.render(<App/>, mountNode);
You can write an animation and put it in.
\n","order":"1"},"codes":{"jsx":"import { Loading } from '@alifd/next';\n\nconst indicator1 = (import { Loading } from '@alifd/next';\n\nconst indicator1 = (<div className=\"load-container load1\">\n <div className=\"loader\">loading...</div>\n</div>);\nconst indicator7 = (<div className=\"load-container load7\">\n <div className=\"loader\">loading...</div>\n</div>);\n\nReactDOM.render(<div>\n <Loading tip=\"default animation\">\n <div className=\"demo\">test</div>\n </Loading>\n <Loading indicator={indicator1}>\n <div className=\"demo\">test</div>\n </Loading>\n <Loading indicator={indicator7}>\n <div className=\"demo\">test</div>\n </Loading>\n</div>, mountNode);
.demo {\n width: 500px;\n background-color: #F2F3F7;\n text-align: center;\n padding:50px;\n}\n.next-loading {\n margin-bottom: 5px;\n}\n\n/* start copy from here */\n\n\n.load-container {\n margin: 0 auto;\n position: relative;\n}\n\n/* animation 1 */\n.load1 .loader,\n.load1 .loader:before,\n.load1 .loader:after {\n background: #5584FF;\n color: #5584FF;\n -webkit-animation: load1 1s infinite ease-in-out;\n animation: load1 1s infinite ease-in-out;\n width: 1em;\n height: 4em;\n}\n.load1 .loader:before,\n.load1 .loader:after {\n position: absolute;\n top: 0;\n content: '';\n}\n.load1 .loader:before {\n left: -1.5em;\n -webkit-animation-delay: -0.32s;\n animation-delay: -0.32s;\n}\n.load1 .loader {\n text-indent: -9999em;\n margin: 0 auto !important;\n position: relative;\n font-size: 11px;\n -webkit-animation-delay: -0.16s;\n animation-delay: -0.16s;\n}\n.load1 .loader:after {\n left: 1.5em;\n}\n@-webkit-keyframes load1 {\n 0%,\n 80%,\n 100% {\n box-shadow: 0 0 ;\n height: 4em;\n }\n 40% {\n box-shadow: 0 -2em ;\n height: 5em;\n }\n}\n@keyframes load1 {\n 0%,\n 80%,\n 100% {\n box-shadow: 0 0 ;\n height: 4em;\n }\n 40% {\n box-shadow: 0 -2em ;\n height: 5em;\n }\n}\n\n\n/* animation 2 */\n.load7 .loader:before,\n.load7 .loader:after,\n.load7 .loader {\n border-radius: 50%;\n width: 2.5em;\n height: 2.5em;\n -webkit-animation-fill-mode: both;\n animation-fill-mode: both;\n -webkit-animation: load7 1.8s infinite ease-in-out;\n animation: load7 1.8s infinite ease-in-out;\n top: -36px;\n}\n.load7 .loader {\n margin: 0 auto !important;\n font-size: 10px;\n position: relative;\n text-indent: -9999em;\n -webkit-animation-delay: -0.16s;\n animation-delay: -0.16s;\n}\n.load7 .loader:before {\n left: -3.5em;\n -webkit-animation-delay: -0.32s;\n animation-delay: -0.32s;\n}\n.load7 .loader:after {\n left: 3.5em;\n}\n.load7 .loader:before,\n.load7 .loader:after {\n content: '';\n position: absolute;\n top: 0;\n}\n@-webkit-keyframes load7 {\n 0%,\n 80%,\n 100% {\n box-shadow: 0 2.5em 0 -1.3em #5584FF;\n }\n 40% {\n box-shadow: 0 2.5em 0 0 #5584FF;\n }\n}\n@keyframes load7 {\n 0%,\n 80%,\n 100% {\n box-shadow: 0 2.5em 0 -1.3em #5584FF;\n }\n 40% {\n box-shadow: 0 2.5em 0 0 #5584FF;\n }\n}
你可以自定义动画,把自己的动画元素传进去, 需要自己写动画样式
\n","order":"1"},"codes":{"jsx":"import { Loading } from '@alifd/next';\n\nconst indicator1 = (import { Loading } from '@alifd/next';\n\nconst indicator1 = (<div className=\"load-container load1\">\n <div className=\"loader\">loading...</div>\n</div>);\nconst indicator7 = (<div className=\"load-container load7\">\n <div className=\"loader\">loading...</div>\n</div>);\n\nReactDOM.render(<div>\n <Loading tip=\"default animation\">\n <div className=\"demo\">test</div>\n </Loading>\n <Loading indicator={indicator1}>\n <div className=\"demo\">test</div>\n </Loading>\n <Loading indicator={indicator7}>\n <div className=\"demo\">test</div>\n </Loading>\n</div>, mountNode);
.demo {\n width: 500px;\n background-color: #F2F3F7;\n text-align: center;\n padding:50px;\n}\n.next-loading {\n margin-bottom: 5px;\n}\n\n/* start copy from here */\n\n\n.load-container {\n margin: 0 auto;\n position: relative;\n}\n\n/* animation 1 */\n.load1 .loader,\n.load1 .loader:before,\n.load1 .loader:after {\n background: #5584FF;\n color: #5584FF;\n -webkit-animation: load1 1s infinite ease-in-out;\n animation: load1 1s infinite ease-in-out;\n width: 1em;\n height: 4em;\n}\n.load1 .loader:before,\n.load1 .loader:after {\n position: absolute;\n top: 0;\n content: '';\n}\n.load1 .loader:before {\n left: -1.5em;\n -webkit-animation-delay: -0.32s;\n animation-delay: -0.32s;\n}\n.load1 .loader {\n text-indent: -9999em;\n margin: 0 auto !important;\n position: relative;\n font-size: 11px;\n -webkit-animation-delay: -0.16s;\n animation-delay: -0.16s;\n}\n.load1 .loader:after {\n left: 1.5em;\n}\n@-webkit-keyframes load1 {\n 0%,\n 80%,\n 100% {\n box-shadow: 0 0 ;\n height: 4em;\n }\n 40% {\n box-shadow: 0 -2em ;\n height: 5em;\n }\n}\n@keyframes load1 {\n 0%,\n 80%,\n 100% {\n box-shadow: 0 0 ;\n height: 4em;\n }\n 40% {\n box-shadow: 0 -2em ;\n height: 5em;\n }\n}\n\n\n/* animation 2 */\n.load7 .loader:before,\n.load7 .loader:after,\n.load7 .loader {\n border-radius: 50%;\n width: 2.5em;\n height: 2.5em;\n -webkit-animation-fill-mode: both;\n animation-fill-mode: both;\n -webkit-animation: load7 1.8s infinite ease-in-out;\n animation: load7 1.8s infinite ease-in-out;\n top: -36px;\n}\n.load7 .loader {\n margin: 0 auto !important;\n font-size: 10px;\n position: relative;\n text-indent: -9999em;\n -webkit-animation-delay: -0.16s;\n animation-delay: -0.16s;\n}\n.load7 .loader:before {\n left: -3.5em;\n -webkit-animation-delay: -0.32s;\n animation-delay: -0.32s;\n}\n.load7 .loader:after {\n left: 3.5em;\n}\n.load7 .loader:before,\n.load7 .loader:after {\n content: '';\n position: absolute;\n top: 0;\n}\n@-webkit-keyframes load7 {\n 0%,\n 80%,\n 100% {\n box-shadow: 0 2.5em 0 -1.3em #5584FF;\n }\n 40% {\n box-shadow: 0 2.5em 0 0 #5584FF;\n }\n}\n@keyframes load7 {\n 0%,\n 80%,\n 100% {\n box-shadow: 0 2.5em 0 -1.3em #5584FF;\n }\n 40% {\n box-shadow: 0 2.5em 0 0 #5584FF;\n }\n}
Sets Loading animation size. it only works for default loading animation.
\n","order":"6"},"codes":{"jsx":"import { Loading } from '@alifd/next';\n\nReactDOM.render(import { Loading } from '@alifd/next';\n\nReactDOM.render(<div>\n <Loading tip=\"normal(size default large)\" >\n <div className=\"demo\">test</div>\n </Loading>\n <Loading tip=\"large\" size=\"large\">\n <div className=\"demo\">test</div>\n </Loading>\n <Loading tip=\"medium\" size=\"medium\">\n <div className=\"demo\">test</div>\n </Loading>\n</div>, mountNode);
.demo {\n width: 500px;\n background-color: #F2F3F7;\n text-align: center;\n padding:50px;\n}\n.next-loading {\n margin-bottom: 5px;\n}
设置Loading动画的尺寸,只对原生的indicator管用
\n","order":"6"},"codes":{"jsx":"import { Loading } from '@alifd/next';\n\nReactDOM.render(import { Loading } from '@alifd/next';\n\nReactDOM.render(<div>\n <Loading tip=\"normal(size default large)\" >\n <div className=\"demo\">test</div>\n </Loading>\n <Loading tip=\"large\" size=\"large\">\n <div className=\"demo\">test</div>\n </Loading>\n <Loading tip=\"medium\" size=\"medium\">\n <div className=\"demo\">test</div>\n </Loading>\n</div>, mountNode);
.demo {\n width: 500px;\n background-color: #F2F3F7;\n text-align: center;\n padding:50px;\n}\n.next-loading {\n margin-bottom: 5px;\n}
Loading state can be toggle。
\n","order":"2"},"codes":{"jsx":"import { Loading, Form, Input, Button } from '@alifd/next';\n\n\nconst FormItem = Form.Item;\n\nconst layout = {\n labelCol: {\n fixedSpan: 4\n },\n wrapperCol: {\n span: 18\n }\n};\n\nclass App extends React.Component {\n constructor(props) {\n super(props);\n this.state = {\n visible: false\n };\n }\n\n setVisible(visible) {\n this.setState({\n visible\n });\n }\n render() {\n return (import { Loading, Form, Input, Button } from '@alifd/next';\n\n\nconst FormItem = Form.Item;\n\nconst layout = {\n labelCol: {\n fixedSpan: 4\n },\n wrapperCol: {\n span: 18\n }\n};\n\nclass App extends React.Component {\n constructor(props) {\n super(props);\n this.state = {\n visible: false\n };\n }\n\n setVisible(visible) {\n this.setState({\n visible\n });\n }\n render() {\n return (<div>\n <Loading visible={this.state.visible} shape=\"fusion-reactor\">\n <Form style={{width: 500}}>\n <FormItem label=\"Username\" {...layout} >\n <Input />\n </FormItem>\n <FormItem label=\"Password\" {...layout} >\n <Input htmlType=\"password\" placeholder=\"please input\"/>\n </FormItem>\n <FormItem label=\"Detail\" {...layout} >\n <Input multiple />\n </FormItem>\n </Form>\n </Loading>\n <div style={{paddingLeft: 80}}>\n <Button onClick={this.setVisible.bind(this, true)} type=\"primary\">Submit</Button>\n <Button onClick={this.setVisible.bind(this, false)} style={{marginLeft: 5}}>Cancel</Button>\n </div>\n </div>);\n }\n}\nReactDOM.render(<App/>, mountNode);
可切换加载状态。
\n","order":"2"},"codes":{"jsx":"import { Loading, Form, Input, Button } from '@alifd/next';\n\n\nconst FormItem = Form.Item;\n\nconst layout = {\n labelCol: {\n fixedSpan: 4\n },\n wrapperCol: {\n span: 18\n }\n};\n\nclass App extends React.Component {\n constructor(props) {\n super(props);\n this.state = {\n visible: false\n };\n }\n\n setVisible(visible) {\n this.setState({\n visible\n });\n }\n render() {\n return (import { Loading, Form, Input, Button } from '@alifd/next';\n\n\nconst FormItem = Form.Item;\n\nconst layout = {\n labelCol: {\n fixedSpan: 4\n },\n wrapperCol: {\n span: 18\n }\n};\n\nclass App extends React.Component {\n constructor(props) {\n super(props);\n this.state = {\n visible: false\n };\n }\n\n setVisible(visible) {\n this.setState({\n visible\n });\n }\n render() {\n return (<div>\n <Loading visible={this.state.visible} shape=\"fusion-reactor\">\n <Form style={{width: 500}}>\n <FormItem label=\"Username\" {...layout} >\n <Input />\n </FormItem>\n <FormItem label=\"Password\" {...layout} >\n <Input htmlType=\"password\" placeholder=\"please input\"/>\n </FormItem>\n <FormItem label=\"Detail\" {...layout} >\n <Input multiple />\n </FormItem>\n </Form>\n </Loading>\n <div style={{paddingLeft: 80}}>\n <Button onClick={this.setVisible.bind(this, true)} type=\"primary\">Submit</Button>\n <Button onClick={this.setVisible.bind(this, false)} style={{marginLeft: 5}}>Cancel</Button>\n </div>\n </div>);\n }\n}\nReactDOM.render(<App/>, mountNode);
Loading state can be toggle。
\n","order":"5"},"codes":{"jsx":"import { Loading } from '@alifd/next';\n\nReactDOM.render(import { Loading } from '@alifd/next';\n\nReactDOM.render(<div>\n <Loading tip=\"default\">\n <div className=\"demo\">test</div>\n </Loading>\n <Loading tip=\"right\" tipAlign=\"right\">\n <div className=\"demo\">test</div>\n </Loading>\n <Loading tip=\"bottom\" tipAlign=\"bottom\">\n <div className=\"demo\">test</div>\n </Loading>\n</div>, mountNode);
.demo {\n width: 500px;\n background-color: #F2F3F7;\n text-align: center;\n padding:50px;\n}\n.next-loading {\n margin-bottom: 5px;\n}
你可以选择提示语的位置,目前支持两个值 right/bottom(默认值)
\n","order":"5"},"codes":{"jsx":"import { Loading } from '@alifd/next';\n\nReactDOM.render(import { Loading } from '@alifd/next';\n\nReactDOM.render(<div>\n <Loading tip=\"default\">\n <div className=\"demo\">test</div>\n </Loading>\n <Loading tip=\"right\" tipAlign=\"right\">\n <div className=\"demo\">test</div>\n </Loading>\n <Loading tip=\"bottom\" tipAlign=\"bottom\">\n <div className=\"demo\">test</div>\n </Loading>\n</div>, mountNode);
.demo {\n width: 500px;\n background-color: #F2F3F7;\n text-align: center;\n padding:50px;\n}\n.next-loading {\n margin-bottom: 5px;\n}
When a part of page is waiting asynchronous data or is rendering, loading animate may reduce anxieties.
\nLoading use the layout display='inline-block'
to wrap inner elements by default.
if you want wrap all the element
, please use <Loading style={{display: 'block'}} />
Param | \nDescripiton | \nType | \nDefault Value | \n
---|---|---|---|
tip | \ncustom text in loading | \nany | \n- | \n
size | \nthe animation size option: 'large' 'medium' | \nEnum | \n'large' | \n
tipAlign | \ntip location option: 'right'(right side of animation) 'bottom'(bottom of animation) | \nEnum | \n'bottom' | \n
visible | \nloading state, default true | \nBoolean | \ntrue | \n
indicator | \ncustom animation | \nany | \n- | \n
color | \nanimation color | \nString | \n- | \n
fullScreen | \nfullscreen display | \nBoolean | \n- | \n
children | \nchildren elements | \nany | \n- | \n
页面局部处于等待异步数据或正在渲染过程时,合适的加载动效会有效缓解用户的焦虑。
\nLoading 默认使用 display='inline-block'
布局的方式包裹内部元素。
如果希望 通栏包裹
可以修改 <Loading style={{display: 'block'}} />
参数 | \n说明 | \n类型 | \n默认值 | \n
---|---|---|---|
tip | \n自定义内容 | \nany | \n- | \n
size | \n设置动画尺寸 可选值: 'large'(大号) 'medium'(中号) | \nEnum | \n'large' | \n
tipAlign | \n自定义内容位置 可选值: 'right'(出现在动画右边) 'bottom'(出现在动画下面) | \nEnum | \n'bottom' | \n
visible | \nloading 状态, 默认 true | \nBoolean | \ntrue | \n
indicator | \n自定义动画 | \nany | \n- | \n
color | \n动画颜色 | \nString | \n- | \n
fullScreen | \n全屏展示 | \nBoolean | \n- | \n
children | \n子元素 | \nany | \n- | \n
inline | \nshould loader be displayed inline | \nBoolean | \ntrue | \n
Use MenuButton as Button.
\n","order":"0"},"codes":{"jsx":"import { MenuButton } from '@alifd/next';\n\nconst { Item } = MenuButton;\nconst menu = ['Undo', 'Redo', 'Cut', 'Copy', 'Paste'].map(item =>import { MenuButton } from '@alifd/next';\n\nconst { Item } = MenuButton;\nconst menu = ['Undo', 'Redo', 'Cut', 'Copy', 'Paste'].map(item => <Item key={item}>{item}</Item>);\n\nReactDOM.render(<div>\n <MenuButton label=\"Document Edit\">{menu}</MenuButton> \n <MenuButton type=\"primary\" label=\"Document Edit\">{menu}</MenuButton> \n <MenuButton type=\"secondary\" label=\"Document Edit\">{menu}</MenuButton><br /><br />\n <MenuButton text label=\"Document Edit\">{menu}</MenuButton> \n <MenuButton text type=\"primary\" label=\"Document Edit\">{menu}</MenuButton> \n <MenuButton text type=\"secondary\" label=\"Document Edit\">{menu}</MenuButton>\n</div>, mountNode);
最简单的用法。支持 Button 的 shape, type, size, component, ghost 等属性透传。
\n","order":"0"},"codes":{"jsx":"import { MenuButton } from '@alifd/next';\n\nconst { Item } = MenuButton;\nconst menu = ['Undo', 'Redo', 'Cut', 'Copy', 'Paste'].map(item =>import { MenuButton } from '@alifd/next';\n\nconst { Item } = MenuButton;\nconst menu = ['Undo', 'Redo', 'Cut', 'Copy', 'Paste'].map(item => <Item key={item}>{item}</Item>);\n\nReactDOM.render(<div>\n <MenuButton label=\"Document Edit\">{menu}</MenuButton> \n <MenuButton type=\"primary\" label=\"Document Edit\">{menu}</MenuButton> \n <MenuButton type=\"secondary\" label=\"Document Edit\">{menu}</MenuButton><br /><br />\n <MenuButton text label=\"Document Edit\">{menu}</MenuButton> \n <MenuButton text type=\"primary\" label=\"Document Edit\">{menu}</MenuButton> \n <MenuButton text type=\"secondary\" label=\"Document Edit\">{menu}</MenuButton>\n</div>, mountNode);
More complex case with custom menu.
\n","order":"2"},"codes":{"jsx":"import { MenuButton } from '@alifd/next';\n\nconst { Item, Group, Divider } = MenuButton;\n\nfunction selectItem(id) {\n console.log(id);\n}\n\nReactDOM.render(import { MenuButton } from '@alifd/next';\n\nconst { Item, Group, Divider } = MenuButton;\n\nfunction selectItem(id) {\n console.log(id);\n}\n\nReactDOM.render(<MenuButton type=\"primary\" label=\"Document Edit\" onItemClick={selectItem}>\n <Item key=\"undo\">Undo</Item>\n <Item key=\"redo\">Redo</Item>\n <Divider />\n <Group>\n <Item key=\"cut\">Cut</Item>\n <Item key=\"copy\">Copy</Item>\n <Item key=\"paste\">Paste</Item>\n </Group>\n</MenuButton>, mountNode);
支持菜单组和菜单分割线,使用方法同 Menu.Group
, Menu.Item
, Menu.Divider
。
import { MenuButton } from '@alifd/next';\n\nconst { Item, Group, Divider } = MenuButton;\n\nfunction selectItem(id) {\n console.log(id);\n}\n\nReactDOM.render(<MenuButton type=\"primary\" label=\"Document Edit\" onItemClick={selectItem}>\n <Item key=\"undo\">Undo</Item>\n <Item key=\"redo\">Redo</Item>\n <Divider />\n <Group>\n <Item key=\"cut\">Cut</Item>\n <Item key=\"copy\">Copy</Item>\n <Item key=\"paste\">Paste</Item>\n </Group>\n</MenuButton>, mountNode);
Change select mode of menu by selectMode
.
import { MenuButton } from '@alifd/next';\n\nconst { Item } = MenuButton;\nconst menu = ['Undo', 'Redo', 'Cut', 'Copy', 'Paste'].map(item => <Item key={item}>{item}</Item>);\n\nReactDOM.render(<div>\n <MenuButton label=\"Document Edit\" selectMode=\"single\" onSelect={keys => console.log(keys)}>{menu}</MenuButton>\n</div>, mountNode);
通过 selectMode 控制菜单的选择模式。
\n","order":"3"},"codes":{"jsx":"import { MenuButton } from '@alifd/next';\n\nconst { Item } = MenuButton;\nconst menu = ['Undo', 'Redo', 'Cut', 'Copy', 'Paste'].map(item =>import { MenuButton } from '@alifd/next';\n\nconst { Item } = MenuButton;\nconst menu = ['Undo', 'Redo', 'Cut', 'Copy', 'Paste'].map(item => <Item key={item}>{item}</Item>);\n\nReactDOM.render(<div>\n <MenuButton label=\"Document Edit\" selectMode=\"single\" onSelect={keys => console.log(keys)}>{menu}</MenuButton>\n</div>, mountNode);
Change component size by size
attribute.
import { MenuButton } from '@alifd/next';\n\nconst { Item } = MenuButton;\nconst menu = ['Undo', 'Redo', 'Cut', 'Copy', 'Paste'].map(item => <Item key={item}>{item}</Item>);\n\nReactDOM.render(<div>\n <MenuButton label=\"Edit Document\" size=\"small\">{menu}</MenuButton> \n <MenuButton label=\"Edit Document\" size=\"medium\">{menu}</MenuButton> \n <MenuButton label=\"Edit Document\" size=\"large\">{menu}</MenuButton>\n</div>, mountNode);
可以通过 size 属性改变按钮大小。
\n","order":"1"},"codes":{"jsx":"import { MenuButton } from '@alifd/next';\n\nconst { Item } = MenuButton;\nconst menu = ['Undo', 'Redo', 'Cut', 'Copy', 'Paste'].map(item =>import { MenuButton } from '@alifd/next';\n\nconst { Item } = MenuButton;\nconst menu = ['Undo', 'Redo', 'Cut', 'Copy', 'Paste'].map(item => <Item key={item}>{item}</Item>);\n\nReactDOM.render(<div>\n <MenuButton label=\"Edit Document\" size=\"small\">{menu}</MenuButton> \n <MenuButton label=\"Edit Document\" size=\"medium\">{menu}</MenuButton> \n <MenuButton label=\"Edit Document\" size=\"large\">{menu}</MenuButton>\n</div>, mountNode);
MenuButton is a button which, when clicked or pressed, will show a context menu.
\nParam | \nDescripiton | \nType | \nDefault Value | \n
---|---|---|---|
label | \nThe text in button | \nReactNode | \n- | \n
autoWidth | \nIf popup width equals to button width | \nBoolean | \ntrue | \n
popupTriggerType | \nTrigger type of popup option: 'click', 'hover' | \nEnum | \n'click' | \n
popupContainer | \nContainer of popup signature: Function() => void | \nFunction | \n- | \n
visible | \nVisible state of popup | \nBoolean | \n- | \n
defaultVisible | \nDefault visible state of popup | \nBoolean | \n- | \n
onVisibleChange | \nCallback when visible state changes signature: Function() => void | \nFunction | \nfunc.noop | \n
popupStyle | \nCustom style of popup | \nObject | \n- | \n
popupClassName | \nCustom className of popup | \nString | \n- | \n
popupProps | \nProps of popup | \nObject | \n- | \n
followTrigger | \nfollow Trigger or not | \nBoolean | \n- | \n
defaultSelectedKeys | \nDefault selected items, as Menu | \nArray | \n[] | \n
selectedKeys | \nSelected items, as Menu | \nArray | \n- | \n
selectMode | \nSelect mode of menu, see Menu | \nString | \n- | \n
onItemClick | \nCallback when click the menu item, see Menu signature: Function() => void | \nFunction | \nfunc.noop | \n
onSelect | \nCallback when select the menu, see Menu signature: Function() => void | \nFunction | \nfunc.noop | \n
menuProps | \nProps of menu | \nObject | \n{} | \n
Item
, Group
, Divider
即 Menu
中对应的子组件,请参考 Menu 文档。参数 | \n说明 | \n类型 | \n默认值 | \n
---|---|---|---|
label | \n按钮上的文本内容 | \nReactNode | \n- | \n
autoWidth | \n弹层是否与按钮宽度相同 | \nBoolean | \ntrue | \n
popupTriggerType | \n弹层触发方式 可选值: 'click', 'hover' | \nEnum | \n'click' | \n
popupContainer | \n弹层容器 签名: Function() => void | \nFunction | \n- | \n
visible | \n弹层展开状态 | \nBoolean | \n- | \n
defaultVisible | \n弹层默认是否展开 | \nBoolean | \n- | \n
onVisibleChange | \n弹层在显示和隐藏触发的事件 签名: Function() => void | \nFunction | \nfunc.noop | \n
popupStyle | \n弹层自定义样式 | \nObject | \n- | \n
popupClassName | \n弹层自定义样式类 | \nString | \n- | \n
popupProps | \n弹层属性透传 | \nObject | \n- | \n
followTrigger | \n是否跟随滚动 | \nBoolean | \n- | \n
defaultSelectedKeys | \n默认激活的菜单项(用法同 Menu 非受控) | \nArray | \n[] | \n
selectedKeys | \n激活的菜单项(用法同 Menu 受控) | \nArray | \n- | \n
selectMode | \n菜单的选择模式,同 Menu 可选值: 'single', 'multiple' | \nEnum | \n- | \n
onItemClick | \n点击菜单项后的回调,同 Menu 签名: Function() => void | \nFunction | \nfunc.noop | \n
onSelect | \n选择菜单后的回调,同 Menu 签名: Function() => void | \nFunction | \nfunc.noop | \n
menuProps | \n菜单属性透传 | \nObject | \n{} | \n
You can make the inline menu expand only one submenu at the same time by setting openMode to 'single'. By default, you can expand more than one at a time.
\n","order":"1"},"codes":{"jsx":"import { Menu } from '@alifd/next';\n\nconst { SubMenu, Item } = Menu;\n\nReactDOM.render(\n \n , mountNode);\n","css":".my-menu {\n width: 200px;\n}\n"},"body":"\n````jsx\nimport { Menu } from '@alifd/next';\n\nconst { SubMenu, Item } = Menu;\n\nReactDOM.render(\n \n , mountNode);\n````\n\n````css\n.my-menu {\n width: 200px;\n}\n````","html":"import { Menu } from '@alifd/next';\n\nconst { SubMenu, Item } = Menu;\n\nReactDOM.render(\n <Menu defaultOpenKeys=\"1\" className=\"my-menu\" openMode=\"single\">\n <SubMenu key=\"0\" label=\"Sub menu 1\">\n <Item key=\"0-0\">Sub option 1</Item>\n <Item key=\"0-1\">Sub option 2</Item>\n <Item key=\"0-2\">Sub option 3</Item>\n </SubMenu>\n <SubMenu key=\"1\" label=\"Sub menu 2\">\n <Item key=\"1-0\">Sub option 1</Item>\n <Item key=\"1-1\">Sub option 2</Item>\n <Item key=\"1-2\">Sub option 3</Item>\n </SubMenu>\n <SubMenu key=\"2\" label=\"Sub menu 3\">\n <Item key=\"2-0\">Sub option 1</Item>\n <Item key=\"2-1\">Sub option 2</Item>\n <Item key=\"2-2\">Sub option 3</Item>\n </SubMenu>\n <SubMenu key=\"3\" label=\"Sub menu 4\">\n <Item key=\"3-0\">Sub option 1</Item>\n <Item key=\"3-1\">Sub option 2</Item>\n <Item key=\"3-2\">Sub option 3</Item>\n </SubMenu>\n </Menu>\n , mountNode);
.my-menu {\n width: 200px;\n}
通过设置 openMode 为 'single',可以让菜单同时只能展开一个内连子菜单,默认为可以同时展开多个。
\n","order":"1"},"codes":{"jsx":"import { Menu } from '@alifd/next';\n\nconst { SubMenu, Item } = Menu;\n\nReactDOM.render(\n \n , mountNode);\n","css":".my-menu {\n width: 200px;\n}\n"},"body":"\n\n````jsx\nimport { Menu } from '@alifd/next';\n\nconst { SubMenu, Item } = Menu;\n\nReactDOM.render(\n \n , mountNode);\n````\n\n````css\n.my-menu {\n width: 200px;\n}\n````","html":"import { Menu } from '@alifd/next';\n\nconst { SubMenu, Item } = Menu;\n\nReactDOM.render(\n <Menu defaultOpenKeys=\"1\" className=\"my-menu\" openMode=\"single\">\n <SubMenu key=\"0\" label=\"Sub menu 1\">\n <Item key=\"0-0\">Sub option 1</Item>\n <Item key=\"0-1\">Sub option 2</Item>\n <Item key=\"0-2\">Sub option 3</Item>\n </SubMenu>\n <SubMenu key=\"1\" label=\"Sub menu 2\">\n <Item key=\"1-0\">Sub option 1</Item>\n <Item key=\"1-1\">Sub option 2</Item>\n <Item key=\"1-2\">Sub option 3</Item>\n </SubMenu>\n <SubMenu key=\"2\" label=\"Sub menu 3\">\n <Item key=\"2-0\">Sub option 1</Item>\n <Item key=\"2-1\">Sub option 2</Item>\n <Item key=\"2-2\">Sub option 3</Item>\n </SubMenu>\n <SubMenu key=\"3\" label=\"Sub menu 4\">\n <Item key=\"3-0\">Sub option 1</Item>\n <Item key=\"3-1\">Sub option 2</Item>\n <Item key=\"3-2\">Sub option 3</Item>\n </SubMenu>\n </Menu>\n , mountNode);
.my-menu {\n width: 200px;\n}
Demo the basic usage.
\n","order":"0"},"codes":{"jsx":"import { Menu } from '@alifd/next';\n\nconst { SubMenu, Item, Group, Divider } = Menu;\n\nReactDOM.render(\n \n , mountNode);\n","css":".my-menu {\n width: 200px;\n}\n"},"body":"\n````jsx\nimport { Menu } from '@alifd/next';\n\nconst { SubMenu, Item, Group, Divider } = Menu;\n\nReactDOM.render(\n \n , mountNode);\n````\n\n````css\n.my-menu {\n width: 200px;\n}\n````","html":"import { Menu } from '@alifd/next';\n\nconst { SubMenu, Item, Group, Divider } = Menu;\n\nReactDOM.render(\n <Menu className=\"my-menu\" defaultOpenKeys=\"sub-menu\">\n <Item key=\"1\">Option 1</Item>\n <Item disabled key=\"2\">Disabled option 2</Item>\n <Divider key=\"divider\" />\n <Group label=\"Group\">\n <Item key=\"group-1\">Group option 1</Item>\n <Item key=\"group-2\">Group option 2</Item>\n </Group>\n <Divider />\n <SubMenu key=\"sub-menu\" label=\"Sub menu\">\n <Item key=\"sub-1\">Sub option 1</Item>\n <Item key=\"sub-2\">Sub option 2</Item>\n <Item disabled key=\"sub-3\">\n <a href=\"https://www.taobao.com/\" target=\"__blank\">Disabled Option Link 3</a>\n </Item>\n <Item key=\"sub-4\">\n <a href=\"https://www.taobao.com/\" target=\"__blank\">Option Link 4</a>\n </Item>\n </SubMenu>\n <Item key=\"3\" helper=\"CTRL+P\">Option 3</Item>\n <Item disabled key=\"4\">\n <a href=\"https://www.taobao.com/\" target=\"__blank\">Disabled Option Link</a>\n </Item>\n <Item key=\"5\">\n <a href=\"https://www.taobao.com/\" target=\"__blank\">Option Link</a>\n </Item>\n </Menu>\n , mountNode);
.my-menu {\n width: 200px;\n}
展示最基本的用法。
\n","order":"0"},"codes":{"jsx":"import { Menu } from '@alifd/next';\n\nconst { SubMenu, Item, Group, Divider } = Menu;\n\nReactDOM.render(\n \n , mountNode);\n","css":".my-menu {\n width: 200px;\n}\n"},"body":"\n\n````jsx\nimport { Menu } from '@alifd/next';\n\nconst { SubMenu, Item, Group, Divider } = Menu;\n\nReactDOM.render(\n \n , mountNode);\n````\n\n````css\n.my-menu {\n width: 200px;\n}\n````","html":"import { Menu } from '@alifd/next';\n\nconst { SubMenu, Item, Group, Divider } = Menu;\n\nReactDOM.render(\n <Menu className=\"my-menu\" defaultOpenKeys=\"sub-menu\">\n <Item key=\"1\">Option 1</Item>\n <Item disabled key=\"2\">Disabled option 2</Item>\n <Divider key=\"divider\" />\n <Group label=\"Group\">\n <Item key=\"group-1\">Group option 1</Item>\n <Item key=\"group-2\">Group option 2</Item>\n </Group>\n <Divider />\n <SubMenu key=\"sub-menu\" label=\"Sub menu\">\n <Item key=\"sub-1\">Sub option 1</Item>\n <Item key=\"sub-2\">Sub option 2</Item>\n <Item disabled key=\"sub-3\">\n <a href=\"https://www.taobao.com/\" target=\"__blank\">Disabled Option Link 3</a>\n </Item>\n <Item key=\"sub-4\">\n <a href=\"https://www.taobao.com/\" target=\"__blank\">Option Link 4</a>\n </Item>\n </SubMenu>\n <Item key=\"3\" helper=\"CTRL+P\">Option 3</Item>\n <Item disabled key=\"4\">\n <a href=\"https://www.taobao.com/\" target=\"__blank\">Disabled Option Link</a>\n </Item>\n <Item key=\"5\">\n <a href=\"https://www.taobao.com/\" target=\"__blank\">Option Link</a>\n </Item>\n </Menu>\n , mountNode);
.my-menu {\n width: 200px;\n}
Demo how to create the custom context menu.
\n","order":"9"},"codes":{"jsx":"import { Menu } from '@alifd/next';\n\nconst { SubMenu, Item, Divider } = Menu;\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n selectedKeys: []\n };\n\n this.handleSelect = this.handleSelect.bind(this);\n }\n\n handleSelect(selectedKeys) {\n selectedKeys = selectedKeys.filter(key => {\n return ['sub-1', 'sub-2'].indexOf(key) > -1;\n });\n this.setState({\n selectedKeys\n });\n }\n\n createContextMenu = e => {\n e.preventDefault();\n\n const target = e.target;\n const { top, left } = target.getBoundingClientRect();\n\n Menu.create({\n target: e.target,\n offset: [e.clientX - left, e.clientY - top],\n className: 'context-menu',\n popupClassName: 'context-menu',\n onItemClick: console.log,\n selectedKeys: this.state.selectedKeys,\n selectMode: 'multiple',\n onSelect: this.handleSelect,\n children: [\nimport { Menu } from '@alifd/next';\n\nconst { SubMenu, Item, Divider } = Menu;\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n selectedKeys: []\n };\n\n this.handleSelect = this.handleSelect.bind(this);\n }\n\n handleSelect(selectedKeys) {\n selectedKeys = selectedKeys.filter(key => {\n return ['sub-1', 'sub-2'].indexOf(key) > -1;\n });\n this.setState({\n selectedKeys\n });\n }\n\n createContextMenu = e => {\n e.preventDefault();\n\n const target = e.target;\n const { top, left } = target.getBoundingClientRect();\n\n Menu.create({\n target: e.target,\n offset: [e.clientX - left, e.clientY - top],\n className: 'context-menu',\n popupClassName: 'context-menu',\n onItemClick: console.log,\n selectedKeys: this.state.selectedKeys,\n selectMode: 'multiple',\n onSelect: this.handleSelect,\n children: [\n <Item key=\"1\">Option 1</Item>,\n <Item key=\"2\">Option 2</Item>,\n <Item key=\"3\">Option 3</Item>,\n <Divider key=\"divider-1\" />,\n <SubMenu key=\"sub-menu\" label=\"Sub menu\">\n <Item key=\"sub-1\">Sub option 1</Item>\n <Item key=\"sub-2\">Sub option 2</Item>\n </SubMenu>,\n <Item key=\"4\">Option 4</Item>,\n <Divider key=\"divider-2\" />,\n <Item key=\"5\">Option 5</Item>\n ]\n });\n };\n\n render() {\n return (\n <div className=\"context-demo\" onContextMenu={this.createContextMenu}>\n Right click here to see the context menu!\n </div>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
.context-demo {\n width: 500px;\n height: 200px;\n line-height: 200px;\n text-align: center;\n background: #DDD;\n border: 1px solid black;\n}\n\n.context-menu {\n width: 120px;\n}
展示如何创建自定义的上下文菜单。
\n","order":"9"},"codes":{"jsx":"import { Menu } from '@alifd/next';\n\nconst { SubMenu, Item, Divider } = Menu;\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n selectedKeys: []\n };\n\n this.handleSelect = this.handleSelect.bind(this);\n }\n\n handleSelect(selectedKeys) {\n selectedKeys = selectedKeys.filter(key => {\n return ['sub-1', 'sub-2'].indexOf(key) > -1;\n });\n this.setState({\n selectedKeys\n });\n }\n\n createContextMenu = e => {\n e.preventDefault();\n\n const target = e.target;\n const { top, left } = target.getBoundingClientRect();\n\n Menu.create({\n target: e.target,\n offset: [e.clientX - left, e.clientY - top],\n className: 'context-menu',\n popupClassName: 'context-menu',\n onItemClick: console.log,\n selectedKeys: this.state.selectedKeys,\n selectMode: 'multiple',\n onSelect: this.handleSelect,\n children: [\nimport { Menu } from '@alifd/next';\n\nconst { SubMenu, Item, Divider } = Menu;\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n selectedKeys: []\n };\n\n this.handleSelect = this.handleSelect.bind(this);\n }\n\n handleSelect(selectedKeys) {\n selectedKeys = selectedKeys.filter(key => {\n return ['sub-1', 'sub-2'].indexOf(key) > -1;\n });\n this.setState({\n selectedKeys\n });\n }\n\n createContextMenu = e => {\n e.preventDefault();\n\n const target = e.target;\n const { top, left } = target.getBoundingClientRect();\n\n Menu.create({\n target: e.target,\n offset: [e.clientX - left, e.clientY - top],\n className: 'context-menu',\n popupClassName: 'context-menu',\n onItemClick: console.log,\n selectedKeys: this.state.selectedKeys,\n selectMode: 'multiple',\n onSelect: this.handleSelect,\n children: [\n <Item key=\"1\">Option 1</Item>,\n <Item key=\"2\">Option 2</Item>,\n <Item key=\"3\">Option 3</Item>,\n <Divider key=\"divider-1\" />,\n <SubMenu key=\"sub-menu\" label=\"Sub menu\">\n <Item key=\"sub-1\">Sub option 1</Item>\n <Item key=\"sub-2\">Sub option 2</Item>\n </SubMenu>,\n <Item key=\"4\">Option 4</Item>,\n <Divider key=\"divider-2\" />,\n <Item key=\"5\">Option 5</Item>\n ]\n });\n };\n\n render() {\n return (\n <div className=\"context-demo\" onContextMenu={this.createContextMenu}>\n Right click here to see the context menu!\n </div>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
.context-demo {\n width: 500px;\n height: 200px;\n line-height: 200px;\n text-align: center;\n background: #DDD;\n border: 1px solid black;\n}\n\n.context-menu {\n width: 120px;\n}
Demo how to customize menu item selection.
\n","order":"7"},"codes":{"jsx":"import { Menu } from '@alifd/next';\n\nconst { CheckboxItem, RadioItem, Divider } = Menu;\n\nconst sexs = ['male', 'female'];\nconst balls = ['football', 'basketball', 'volleyball'];\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n sex: 'male',\n balls: []\n };\n\n this.handleSexCheck = this.handleSexCheck.bind(this);\n this.handleBallCheck = this.handleBallCheck.bind(this);\n }\n\n handleSexCheck(key) {\n this.setState({\n sex: key\n });\n }\n\n handleBallCheck(key, check) {\n let newKeys;\n const index = this.state.balls.indexOf(key);\n if (check && index === -1) {\n newKeys = this.state.balls.concat(key);\n } else if (!check && index > -1) {\n newKeys = [\n ...this.state.balls.slice(0, index),\n ...this.state.balls.slice(index + 1)\n ];\n }\n\n if (newKeys) {\n this.setState({\n balls: newKeys\n });\n }\n }\n\n render() {\n return (\n \n );\n }\n}\n\nReactDOM.render(import { Menu } from '@alifd/next';\n\nconst { CheckboxItem, RadioItem, Divider } = Menu;\n\nconst sexs = ['male', 'female'];\nconst balls = ['football', 'basketball', 'volleyball'];\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n sex: 'male',\n balls: []\n };\n\n this.handleSexCheck = this.handleSexCheck.bind(this);\n this.handleBallCheck = this.handleBallCheck.bind(this);\n }\n\n handleSexCheck(key) {\n this.setState({\n sex: key\n });\n }\n\n handleBallCheck(key, check) {\n let newKeys;\n const index = this.state.balls.indexOf(key);\n if (check && index === -1) {\n newKeys = this.state.balls.concat(key);\n } else if (!check && index > -1) {\n newKeys = [\n ...this.state.balls.slice(0, index),\n ...this.state.balls.slice(index + 1)\n ];\n }\n\n if (newKeys) {\n this.setState({\n balls: newKeys\n });\n }\n }\n\n render() {\n return (\n <Menu className=\"my-menu\">\n {sexs.map(sex => (\n <RadioItem key={sex} checked={this.state.sex === sex} onChange={this.handleSexCheck.bind(this, sex)}>\n {sex}\n </RadioItem>\n ))}\n <Divider key=\"divider\" />\n {balls.map(ball => (\n <CheckboxItem key={ball} checked={this.state.balls.indexOf(ball) > -1} onChange={this.handleBallCheck.bind(this, ball)}>\n {ball}\n </CheckboxItem>\n ))}\n </Menu>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
.my-menu {\n width: 200px;\n}
展示自定义组合菜单项可选的用法。
\n","order":"7"},"codes":{"jsx":"import { Menu } from '@alifd/next';\n\nconst { CheckboxItem, RadioItem, Divider } = Menu;\n\nconst sexs = ['male', 'female'];\nconst balls = ['football', 'basketball', 'volleyball'];\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n sex: 'male',\n balls: []\n };\n\n this.handleSexCheck = this.handleSexCheck.bind(this);\n this.handleBallCheck = this.handleBallCheck.bind(this);\n }\n\n handleSexCheck(key) {\n this.setState({\n sex: key\n });\n }\n\n handleBallCheck(key, check) {\n let newKeys;\n const index = this.state.balls.indexOf(key);\n if (check && index === -1) {\n newKeys = this.state.balls.concat(key);\n } else if (!check && index > -1) {\n newKeys = [\n ...this.state.balls.slice(0, index),\n ...this.state.balls.slice(index + 1)\n ];\n }\n\n if (newKeys) {\n this.setState({\n balls: newKeys\n });\n }\n }\n\n render() {\n return (\n \n );\n }\n}\n\nReactDOM.render(import { Menu } from '@alifd/next';\n\nconst { CheckboxItem, RadioItem, Divider } = Menu;\n\nconst sexs = ['male', 'female'];\nconst balls = ['football', 'basketball', 'volleyball'];\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n sex: 'male',\n balls: []\n };\n\n this.handleSexCheck = this.handleSexCheck.bind(this);\n this.handleBallCheck = this.handleBallCheck.bind(this);\n }\n\n handleSexCheck(key) {\n this.setState({\n sex: key\n });\n }\n\n handleBallCheck(key, check) {\n let newKeys;\n const index = this.state.balls.indexOf(key);\n if (check && index === -1) {\n newKeys = this.state.balls.concat(key);\n } else if (!check && index > -1) {\n newKeys = [\n ...this.state.balls.slice(0, index),\n ...this.state.balls.slice(index + 1)\n ];\n }\n\n if (newKeys) {\n this.setState({\n balls: newKeys\n });\n }\n }\n\n render() {\n return (\n <Menu className=\"my-menu\">\n {sexs.map(sex => (\n <RadioItem key={sex} checked={this.state.sex === sex} onChange={this.handleSexCheck.bind(this, sex)}>\n {sex}\n </RadioItem>\n ))}\n <Divider key=\"divider\" />\n {balls.map(ball => (\n <CheckboxItem key={ball} checked={this.state.balls.indexOf(ball) > -1} onChange={this.handleBallCheck.bind(this, ball)}>\n {ball}\n </CheckboxItem>\n ))}\n </Menu>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
.my-menu {\n width: 200px;\n}
Demo how to customize pop up content.
\n","order":"5"},"codes":{"jsx":"import { Menu } from '@alifd/next';\n\nconst { PopupItem } = Menu;\n\nclass Demo extends React.Component {\n render() {\n const popupProps = {\n target: () => ReactDOM.findDOMNode(this),\n offset: [-1, 0],\n animation: false\n };\n\n return (\n \n );\n }\n}\n\nReactDOM.render(import { Menu } from '@alifd/next';\n\nconst { PopupItem } = Menu;\n\nclass Demo extends React.Component {\n render() {\n const popupProps = {\n target: () => ReactDOM.findDOMNode(this),\n offset: [-1, 0],\n animation: false\n };\n\n return (\n <Menu className=\"my-custom-menu\" popupProps={popupProps}>\n <PopupItem key=\"0\" label=\"Popup item 1\">\n <div className=\"my-custom-content\">Custom content 1</div>\n </PopupItem>\n <PopupItem key=\"1\" label=\"Popup item 2\">\n <div className=\"my-custom-content\">Custom content 2</div>\n </PopupItem>\n <PopupItem key=\"2\" label=\"Popup item 3\">\n <div className=\"my-custom-content\">Custom content 3</div>\n </PopupItem>\n <PopupItem key=\"3\" label=\"Popup item 4\">\n <div className=\"my-custom-content\">Custom content 4</div>\n </PopupItem>\n </Menu>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
.my-custom-menu {\n width: 200px;\n border: 1px solid #ccc;\n padding: 0;\n box-shadow: none;\n z-index: 1000;\n}\n\n.my-custom-content {\n width: 400px;\n height: 200px;\n background: #fff;\n border: 1px solid #ccc;\n line-height: 200px;\n text-align: center;\n font-size: 20px;\n}
自定义菜单弹出内容。
\n","order":"5"},"codes":{"jsx":"import { Menu } from '@alifd/next';\n\nconst { PopupItem } = Menu;\n\nclass Demo extends React.Component {\n render() {\n const popupProps = {\n target: () => ReactDOM.findDOMNode(this),\n offset: [-1, 0],\n animation: false\n };\n\n return (\n \n );\n }\n}\n\nReactDOM.render(import { Menu } from '@alifd/next';\n\nconst { PopupItem } = Menu;\n\nclass Demo extends React.Component {\n render() {\n const popupProps = {\n target: () => ReactDOM.findDOMNode(this),\n offset: [-1, 0],\n animation: false\n };\n\n return (\n <Menu className=\"my-custom-menu\" popupProps={popupProps}>\n <PopupItem key=\"0\" label=\"Popup item 1\">\n <div className=\"my-custom-content\">Custom content 1</div>\n </PopupItem>\n <PopupItem key=\"1\" label=\"Popup item 2\">\n <div className=\"my-custom-content\">Custom content 2</div>\n </PopupItem>\n <PopupItem key=\"2\" label=\"Popup item 3\">\n <div className=\"my-custom-content\">Custom content 3</div>\n </PopupItem>\n <PopupItem key=\"3\" label=\"Popup item 4\">\n <div className=\"my-custom-content\">Custom content 4</div>\n </PopupItem>\n </Menu>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
.my-custom-menu {\n width: 200px;\n border: 1px solid #ccc;\n padding: 0;\n box-shadow: none;\n z-index: 1000;\n}\n\n.my-custom-content {\n width: 400px;\n height: 200px;\n background: #fff;\n border: 1px solid #ccc;\n line-height: 200px;\n text-align: center;\n font-size: 20px;\n}
You can set the triggerType to 'hover' to hover to open the submenu. By default, click to open the submenu.
\n","order":"3"},"codes":{"jsx":"import { Menu } from '@alifd/next';\n\nconst { SubMenu, Item, Divider } = Menu;\n\nReactDOM.render(\n \n , mountNode);\n","css":".my-menu {\n width: 200px;\n}\n"},"body":"\n````jsx\nimport { Menu } from '@alifd/next';\n\nconst { SubMenu, Item, Divider } = Menu;\n\nReactDOM.render(\n \n , mountNode);\n````\n\n````css\n.my-menu {\n width: 200px;\n}\n````","html":"import { Menu } from '@alifd/next';\n\nconst { SubMenu, Item, Divider } = Menu;\n\nReactDOM.render(\n <Menu className=\"my-menu\" mode=\"popup\" triggerType=\"hover\">\n <Item key=\"1\">Option 1</Item>\n <Item key=\"2\">Option 2</Item>\n <Item key=\"3\">Option 3</Item>\n <Divider key=\"divider\" />\n <SubMenu key=\"sub-1\" label=\"Popup menu 1\">\n <Item key=\"popup-1-1\">Popup option 1</Item>\n <Item key=\"popup-1-2\">Popup option 2</Item>\n </SubMenu>\n <SubMenu key=\"sub-2\" label=\"Popup menu 2\">\n <Item key=\"popup-2-1\">Popup option 1</Item>\n <Item key=\"popup-2-2\">Popup option 2</Item>\n </SubMenu>\n </Menu>\n , mountNode);
.my-menu {\n width: 200px;\n}
可以设置 triggerType 为 'hover',来 hover 打开子菜单,默认点击打开子菜单。
\n","order":"3"},"codes":{"jsx":"import { Menu } from '@alifd/next';\n\nconst { SubMenu, Item, Divider } = Menu;\n\nReactDOM.render(\n \n , mountNode);\n","css":".my-menu {\n width: 200px;\n}\n"},"body":"\n\n````jsx\nimport { Menu } from '@alifd/next';\n\nconst { SubMenu, Item, Divider } = Menu;\n\nReactDOM.render(\n \n , mountNode);\n````\n\n````css\n.my-menu {\n width: 200px;\n}\n````","html":"import { Menu } from '@alifd/next';\n\nconst { SubMenu, Item, Divider } = Menu;\n\nReactDOM.render(\n <Menu className=\"my-menu\" mode=\"popup\" triggerType=\"hover\">\n <Item key=\"1\">Option 1</Item>\n <Item key=\"2\">Option 2</Item>\n <Item key=\"3\">Option 3</Item>\n <Divider key=\"divider\" />\n <SubMenu key=\"sub-1\" label=\"Popup menu 1\">\n <Item key=\"popup-1-1\">Popup option 1</Item>\n <Item key=\"popup-1-2\">Popup option 2</Item>\n </SubMenu>\n <SubMenu key=\"sub-2\" label=\"Popup menu 2\">\n <Item key=\"popup-2-1\">Popup option 1</Item>\n <Item key=\"popup-2-2\">Popup option 2</Item>\n </SubMenu>\n </Menu>\n , mountNode);
.my-menu {\n width: 200px;\n}
Demo the usage of the horizontal navigation menu bar.
\n","order":"8"},"codes":{"jsx":"import { Menu } from '@alifd/next';\n\nconst { SubMenu, Item } = Menu;\n\nReactDOM.render(\n \n , mountNode);\n","css":".my-hoz-menu .next-menu-item {\n width: 160px;\n}\n.my-hoz-menu .next-menu-item.next-menu-more {\n width: 40px;\n}\n"},"body":"\n````jsx\nimport { Menu } from '@alifd/next';\n\nconst { SubMenu, Item } = Menu;\n\nReactDOM.render(\n \n , mountNode);\n````\n\n````css\n.my-hoz-menu .next-menu-item {\n width: 160px;\n}\n.my-hoz-menu .next-menu-item.next-menu-more {\n width: 40px;\n}\n````","html":"import { Menu } from '@alifd/next';\n\nconst { SubMenu, Item } = Menu;\n\nReactDOM.render(\n <Menu hozInLine direction=\"hoz\" mode=\"popup\" className=\"my-hoz-menu\" popupClassName=\"my-hoz-menu\" popupAutoWidth>\n <Item key=\"1\">First</Item>\n <Item key=\"2\">Second</Item>\n <SubMenu label=\"Sub Nav\">\n <Item key=\"sub-12\">Sub option 1</Item>\n <Item key=\"sub-22\">Sub option 2</Item>\n <SubMenu label=\"Sub Sub Nav\">\n <Item key=\"sub-sub-122\">Sub sub option 1</Item>\n <Item key=\"sub-sub-222\">Sub sub option 2</Item>\n </SubMenu>\n </SubMenu>\n <SubMenu label=\"Sub Nav\">\n <Item key=\"sub-1\">Sub option 1</Item>\n <Item key=\"sub-2\">Sub option 2</Item>\n <SubMenu label=\"Sub Sub Nav\">\n <Item key=\"sub-sub-1\">Sub sub option 1</Item>\n <Item key=\"sub-sub-2\">Sub sub option 2</Item>\n </SubMenu>\n </SubMenu>\n <Item key=\"3\">Third</Item>\n </Menu>\n , mountNode);
.my-hoz-menu .next-menu-item {\n width: 160px;\n}\n.my-hoz-menu .next-menu-item.next-menu-more {\n width: 40px;\n}
展示横向导航菜单条的用法。
\n","order":"8"},"codes":{"jsx":"import { Menu } from '@alifd/next';\n\nconst { SubMenu, Item } = Menu;\n\nReactDOM.render(\n \n , mountNode);\n","css":".my-hoz-menu .next-menu-item {\n width: 160px;\n}\n.my-hoz-menu .next-menu-item.next-menu-more {\n width: 40px;\n}\n"},"body":"\n\n````jsx\nimport { Menu } from '@alifd/next';\n\nconst { SubMenu, Item } = Menu;\n\nReactDOM.render(\n \n , mountNode);\n````\n\n````css\n.my-hoz-menu .next-menu-item {\n width: 160px;\n}\n.my-hoz-menu .next-menu-item.next-menu-more {\n width: 40px;\n}\n````","html":"import { Menu } from '@alifd/next';\n\nconst { SubMenu, Item } = Menu;\n\nReactDOM.render(\n <Menu hozInLine direction=\"hoz\" mode=\"popup\" className=\"my-hoz-menu\" popupClassName=\"my-hoz-menu\" popupAutoWidth>\n <Item key=\"1\">First</Item>\n <Item key=\"2\">Second</Item>\n <SubMenu label=\"Sub Nav\">\n <Item key=\"sub-12\">Sub option 1</Item>\n <Item key=\"sub-22\">Sub option 2</Item>\n <SubMenu label=\"Sub Sub Nav\">\n <Item key=\"sub-sub-122\">Sub sub option 1</Item>\n <Item key=\"sub-sub-222\">Sub sub option 2</Item>\n </SubMenu>\n </SubMenu>\n <SubMenu label=\"Sub Nav\">\n <Item key=\"sub-1\">Sub option 1</Item>\n <Item key=\"sub-2\">Sub option 2</Item>\n <SubMenu label=\"Sub Sub Nav\">\n <Item key=\"sub-sub-1\">Sub sub option 1</Item>\n <Item key=\"sub-sub-2\">Sub sub option 2</Item>\n </SubMenu>\n </SubMenu>\n <Item key=\"3\">Third</Item>\n </Menu>\n , mountNode);
.my-hoz-menu .next-menu-item {\n width: 160px;\n}\n.my-hoz-menu .next-menu-item.next-menu-more {\n width: 40px;\n}
You can align the popup menu with the parent menu by setting popupAlign to 'outside'.
\n","order":"4"},"codes":{"jsx":"import { Menu } from '@alifd/next';\n\nconst { SubMenu, Item, Divider } = Menu;\n\nReactDOM.render(\n \n , mountNode);\n","css":".my-menu {\n width: 200px;\n}\n"},"body":"\n````jsx\nimport { Menu } from '@alifd/next';\n\nconst { SubMenu, Item, Divider } = Menu;\n\nReactDOM.render(\n \n , mountNode);\n````\n\n````css\n.my-menu {\n width: 200px;\n}\n````","html":"import { Menu } from '@alifd/next';\n\nconst { SubMenu, Item, Divider } = Menu;\n\nReactDOM.render(\n <Menu className=\"my-menu\" mode=\"popup\" popupAlign=\"outside\">\n <Item key=\"1\">Option 1</Item>\n <Item key=\"2\">Option 2</Item>\n <Item key=\"3\">Option 3</Item>\n <Divider key=\"divider\" />\n <SubMenu key=\"sub-1\" label=\"Popup menu 1\">\n <Item key=\"popup-1-1\">Popup option 1</Item>\n <Item key=\"popup-1-2\">Popup option 2</Item>\n </SubMenu>\n <SubMenu key=\"sub-2\" label=\"Popup menu 2\">\n <Item key=\"popup-2-1\">Popup option 1</Item>\n <Item key=\"popup-2-2\">Popup option 2</Item>\n </SubMenu>\n </Menu>\n , mountNode);
.my-menu {\n width: 200px;\n}
可以通过设置 popupAlign 为 'outside',使弹出菜单和父级菜单对齐。
\n","order":"4"},"codes":{"jsx":"import { Menu } from '@alifd/next';\n\nconst { SubMenu, Item, Divider } = Menu;\n\nReactDOM.render(\n \n , mountNode);\n","css":".my-menu {\n width: 200px;\n}\n"},"body":"\n\n````jsx\nimport { Menu } from '@alifd/next';\n\nconst { SubMenu, Item, Divider } = Menu;\n\nReactDOM.render(\n \n , mountNode);\n````\n\n````css\n.my-menu {\n width: 200px;\n}\n````","html":"import { Menu } from '@alifd/next';\n\nconst { SubMenu, Item, Divider } = Menu;\n\nReactDOM.render(\n <Menu className=\"my-menu\" mode=\"popup\" popupAlign=\"outside\">\n <Item key=\"1\">Option 1</Item>\n <Item key=\"2\">Option 2</Item>\n <Item key=\"3\">Option 3</Item>\n <Divider key=\"divider\" />\n <SubMenu key=\"sub-1\" label=\"Popup menu 1\">\n <Item key=\"popup-1-1\">Popup option 1</Item>\n <Item key=\"popup-1-2\">Popup option 2</Item>\n </SubMenu>\n <SubMenu key=\"sub-2\" label=\"Popup menu 2\">\n <Item key=\"popup-2-1\">Popup option 1</Item>\n <Item key=\"popup-2-2\">Popup option 2</Item>\n </SubMenu>\n </Menu>\n , mountNode);
.my-menu {\n width: 200px;\n}
Demo the usage of the popup up menu.
\n","order":"2"},"codes":{"jsx":"import { Menu } from '@alifd/next';\n\nconst { SubMenu, Item, Divider } = Menu;\n\nReactDOM.render(\n \n , mountNode);\n","css":".my-menu {\n width: 200px;\n}\n"},"body":"\n````jsx\nimport { Menu } from '@alifd/next';\n\nconst { SubMenu, Item, Divider } = Menu;\n\nReactDOM.render(\n \n , mountNode);\n````\n\n````css\n.my-menu {\n width: 200px;\n}\n````","html":"import { Menu } from '@alifd/next';\n\nconst { SubMenu, Item, Divider } = Menu;\n\nReactDOM.render(\n <Menu className=\"my-menu\" mode=\"popup\">\n <Item key=\"1\">Option 1</Item>\n <Item key=\"2\">Option 2</Item>\n <Item key=\"3\">Option 3</Item>\n <Divider key=\"divider\" />\n <SubMenu key=\"sub-1\" label=\"Popup menu 1\">\n <Item key=\"popup-1-1\">Popup option 1</Item>\n <Item key=\"popup-1-2\">Popup option 2</Item>\n </SubMenu>\n <SubMenu key=\"sub-2\" label=\"Popup menu 2\">\n <Item key=\"popup-2-1\">Popup option 1</Item>\n <Item key=\"popup-2-2\">Popup option 2</Item>\n </SubMenu>\n </Menu>\n , mountNode);
.my-menu {\n width: 200px;\n}
展示弹出菜单的用法。
\n","order":"2"},"codes":{"jsx":"import { Menu } from '@alifd/next';\n\nconst { SubMenu, Item, Divider } = Menu;\n\nReactDOM.render(\n \n , mountNode);\n","css":".my-menu {\n width: 200px;\n}\n"},"body":"\n\n````jsx\nimport { Menu } from '@alifd/next';\n\nconst { SubMenu, Item, Divider } = Menu;\n\nReactDOM.render(\n \n , mountNode);\n````\n\n````css\n.my-menu {\n width: 200px;\n}\n````","html":"import { Menu } from '@alifd/next';\n\nconst { SubMenu, Item, Divider } = Menu;\n\nReactDOM.render(\n <Menu className=\"my-menu\" mode=\"popup\">\n <Item key=\"1\">Option 1</Item>\n <Item key=\"2\">Option 2</Item>\n <Item key=\"3\">Option 3</Item>\n <Divider key=\"divider\" />\n <SubMenu key=\"sub-1\" label=\"Popup menu 1\">\n <Item key=\"popup-1-1\">Popup option 1</Item>\n <Item key=\"popup-1-2\">Popup option 2</Item>\n </SubMenu>\n <SubMenu key=\"sub-2\" label=\"Popup menu 2\">\n <Item key=\"popup-2-1\">Popup option 1</Item>\n <Item key=\"popup-2-2\">Popup option 2</Item>\n </SubMenu>\n </Menu>\n , mountNode);
.my-menu {\n width: 200px;\n}
Demo the usage of menu item selection.
\n","order":"6"},"codes":{"jsx":"import { Switch, Menu } from '@alifd/next';\n\nconst { SubMenu, Item } = Menu;\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n multiple: false,\n subMenuSelectable: false,\n shallowSelect: false,\n isSelectIconRight: false,\n selectedKeys: ['1']\n };\n\n [\n 'handleMultipleChange', 'handleSubMenuSelectableChange',\n 'handleShallowSelectChange', 'handleSelect', 'handleIconDirectionChange'\n ].forEach(method => {\n this[method] = this[method].bind(this);\n });\n }\n\n handleMultipleChange() {\n this.setState({\n multiple: !this.state.multiple,\n selectedKeys: []\n });\n }\n\n handleIconDirectionChange() {\n this.setState({\n isSelectIconRight: !this.state.isSelectIconRight,\n selectedKeys: []\n });\n }\n\n handleSubMenuSelectableChange() {\n this.setState({\n subMenuSelectable: !this.state.subMenuSelectable,\n selectedKeys: []\n });\n }\n\n handleShallowSelectChange() {\n this.setState({\n shallowSelect: !this.state.shallowSelect,\n selectedKeys: []\n });\n }\n\n handleSelect(selectedKeys, ...others) {\n this.setState({\n selectedKeys\n });\n\n console.log(selectedKeys, ...others);\n }\n\n render() {\n const { multiple, subMenuSelectable, shallowSelect, selectedKeys, isSelectIconRight } = this.state;\n const selectMode = multiple ? 'multiple' : 'single';\n\n return (\nimport { Switch, Menu } from '@alifd/next';\n\nconst { SubMenu, Item } = Menu;\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n multiple: false,\n subMenuSelectable: false,\n shallowSelect: false,\n isSelectIconRight: false,\n selectedKeys: ['1']\n };\n\n [\n 'handleMultipleChange', 'handleSubMenuSelectableChange',\n 'handleShallowSelectChange', 'handleSelect', 'handleIconDirectionChange'\n ].forEach(method => {\n this[method] = this[method].bind(this);\n });\n }\n\n handleMultipleChange() {\n this.setState({\n multiple: !this.state.multiple,\n selectedKeys: []\n });\n }\n\n handleIconDirectionChange() {\n this.setState({\n isSelectIconRight: !this.state.isSelectIconRight,\n selectedKeys: []\n });\n }\n\n handleSubMenuSelectableChange() {\n this.setState({\n subMenuSelectable: !this.state.subMenuSelectable,\n selectedKeys: []\n });\n }\n\n handleShallowSelectChange() {\n this.setState({\n shallowSelect: !this.state.shallowSelect,\n selectedKeys: []\n });\n }\n\n handleSelect(selectedKeys, ...others) {\n this.setState({\n selectedKeys\n });\n\n console.log(selectedKeys, ...others);\n }\n\n render() {\n const { multiple, subMenuSelectable, shallowSelect, selectedKeys, isSelectIconRight } = this.state;\n const selectMode = multiple ? 'multiple' : 'single';\n\n return (\n <div>\n <div>\n <span className=\"my-switch-label\">Multiple </span>\n <Switch value={multiple} onChange={this.handleMultipleChange} />\n </div>\n <div>\n <span className=\"my-switch-label\">isSelectIconRight </span>\n <Switch value={multiple} onChange={this.handleIconDirectionChange} />\n </div>\n <div>\n <span className=\"my-switch-label\">Label of submenu selectable </span>\n <Switch value={multiple} onChange={this.handleSubMenuSelectableChange} />\n </div>\n <div>\n <span className=\"my-switch-label\">Only first level selectable </span>\n <Switch value={multiple} onChange={this.handleShallowSelectChange} />\n </div>\n <Menu isSelectIconRight={isSelectIconRight} className=\"my-select-menu\" defaultOpenKeys={['sub']} selectMode={selectMode} selectedKeys={selectedKeys} shallowSelect={shallowSelect} onSelect={this.handleSelect}>\n <Item key=\"1\">Option 1</Item>\n <Item disabled key=\"2\">Disabled option 2</Item>\n <SubMenu key=\"sub\" label=\"Sub menu\" selectable={subMenuSelectable}>\n <Item key=\"sub-1\">Sub option 1</Item>\n <Item key=\"sub-2\">Sub option 2</Item>\n </SubMenu>\n <Item key=\"3\">Option 3</Item>\n </Menu>\n </div>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
.my-switch-label {\n vertical-align: super;\n}\n\n.my-select-menu {\n margin-top: 10px;\n width: 200px;\n}
展示菜单项选择用法。
\n","order":"6"},"codes":{"jsx":"import { Switch, Menu } from '@alifd/next';\n\nconst { SubMenu, Item } = Menu;\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n multiple: false,\n subMenuSelectable: false,\n shallowSelect: false,\n isSelectIconRight: false,\n selectedKeys: ['1']\n };\n\n [\n 'handleMultipleChange', 'handleSubMenuSelectableChange',\n 'handleShallowSelectChange', 'handleSelect', 'handleIconDirectionChange'\n ].forEach(method => {\n this[method] = this[method].bind(this);\n });\n }\n\n handleMultipleChange() {\n this.setState({\n multiple: !this.state.multiple,\n selectedKeys: []\n });\n }\n\n handleIconDirectionChange() {\n this.setState({\n isSelectIconRight: !this.state.isSelectIconRight,\n selectedKeys: []\n });\n }\n\n handleSubMenuSelectableChange() {\n this.setState({\n subMenuSelectable: !this.state.subMenuSelectable,\n selectedKeys: []\n });\n }\n\n handleShallowSelectChange() {\n this.setState({\n shallowSelect: !this.state.shallowSelect,\n selectedKeys: []\n });\n }\n\n handleSelect(selectedKeys, ...others) {\n this.setState({\n selectedKeys\n });\n\n console.log(selectedKeys, ...others);\n }\n\n render() {\n const { multiple, subMenuSelectable, shallowSelect, selectedKeys, isSelectIconRight } = this.state;\n const selectMode = multiple ? 'multiple' : 'single';\n\n return (\nimport { Switch, Menu } from '@alifd/next';\n\nconst { SubMenu, Item } = Menu;\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n multiple: false,\n subMenuSelectable: false,\n shallowSelect: false,\n isSelectIconRight: false,\n selectedKeys: ['1']\n };\n\n [\n 'handleMultipleChange', 'handleSubMenuSelectableChange',\n 'handleShallowSelectChange', 'handleSelect', 'handleIconDirectionChange'\n ].forEach(method => {\n this[method] = this[method].bind(this);\n });\n }\n\n handleMultipleChange() {\n this.setState({\n multiple: !this.state.multiple,\n selectedKeys: []\n });\n }\n\n handleIconDirectionChange() {\n this.setState({\n isSelectIconRight: !this.state.isSelectIconRight,\n selectedKeys: []\n });\n }\n\n handleSubMenuSelectableChange() {\n this.setState({\n subMenuSelectable: !this.state.subMenuSelectable,\n selectedKeys: []\n });\n }\n\n handleShallowSelectChange() {\n this.setState({\n shallowSelect: !this.state.shallowSelect,\n selectedKeys: []\n });\n }\n\n handleSelect(selectedKeys, ...others) {\n this.setState({\n selectedKeys\n });\n\n console.log(selectedKeys, ...others);\n }\n\n render() {\n const { multiple, subMenuSelectable, shallowSelect, selectedKeys, isSelectIconRight } = this.state;\n const selectMode = multiple ? 'multiple' : 'single';\n\n return (\n <div>\n <div>\n <span className=\"my-switch-label\">Multiple </span>\n <Switch value={multiple} onChange={this.handleMultipleChange} />\n </div>\n <div>\n <span className=\"my-switch-label\">isSelectIconRight </span>\n <Switch value={multiple} onChange={this.handleIconDirectionChange} />\n </div>\n <div>\n <span className=\"my-switch-label\">Label of submenu selectable </span>\n <Switch value={multiple} onChange={this.handleSubMenuSelectableChange} />\n </div>\n <div>\n <span className=\"my-switch-label\">Only first level selectable </span>\n <Switch value={multiple} onChange={this.handleShallowSelectChange} />\n </div>\n <Menu isSelectIconRight={isSelectIconRight} className=\"my-select-menu\" defaultOpenKeys={['sub']} selectMode={selectMode} selectedKeys={selectedKeys} shallowSelect={shallowSelect} onSelect={this.handleSelect}>\n <Item key=\"1\">Option 1</Item>\n <Item disabled key=\"2\">Disabled option 2</Item>\n <SubMenu key=\"sub\" label=\"Sub menu\" selectable={subMenuSelectable}>\n <Item key=\"sub-1\">Sub option 1</Item>\n <Item key=\"sub-2\">Sub option 2</Item>\n </SubMenu>\n <Item key=\"3\">Option 3</Item>\n </Menu>\n </div>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
.my-switch-label {\n vertical-align: super;\n}\n\n.my-select-menu {\n margin-top: 10px;\n width: 200px;\n}
Param | \nDescripiton | \nType | \nDefault Value | \n
---|---|---|---|
children | \nsubmenu and menu item | \nReactNode | \n- | \n
onItemClick | \ncallback function triggered when click the menu item signatures: Function(key: String, item: Object, event: Object) => void params: key: {String} key of clicked menu item item: {Object} clicked menu item event: {Object} clicked event | \nFunction | \n() => {} | \n
openKeys | \nkeys of open submenu currently | \nString/Array | \n- | \n
defaultOpenKeys | \nkeys of open submenu in default | \nString/Array | \n[] | \n
defaultOpenAll | \nopen all submenus default, only when mode is set to 'inline' and openMode is set to 'multiple', priority is higher than defaultOpenKeys | \nBoolean | \nfalse | \n
onOpen | \ncallback function triggered when open or close the submenu signatures: Function(key: String, extra: Object) => void params: key: {String} keys of open submenu extra: {Object} extra param extra.key: {String} key of current operation submenu extra.open: {Boolean} whether is open | \nFunction | \n() => {} | \n
mode | \nopen mode of submenu options: 'inline', 'popup' | \nEnum | \n'inline' | \n
triggerType | \nopen trigger type of submenu option: 'click', 'hover' | \nEnum | \n'click' | \n
openMode | \nexpand mode of the inline submenu, expand a submenu or multiple submenus at the same time, it only works when mode is inline options: 'single', 'multiple' | \nEnum | \n'multiple' | \n
inlineIndent | \nindent of inline submenu | \nNumber | \n20 | \n
popupAutoWidth | \nwhether the width of the pop up submenu is equal to the parent menu item, if the width of the pop up submenu is smaller than the parent menu item, it will be the same as the parent menu item, otherwise do nothing. | \nBoolean | \nfalse | \n
popupAlign | \nalignment of the pop up submenu options: 'follow', 'outside' | \nEnum | \n'follow' | \n
popupProps | \nproperties of Popup | \nObject/Function | \n{} | \n
popupClassName | \nclassName of the pop up submenu | \nString | \n- | \n
popupStyle | \nstyle of the pop up submenu | \nObject | \n- | \n
selectedKeys | \nkeys of selected menu item currently | \nString/Array | \n- | \n
defaultSelectedKeys | \nkeys of selected menu item in default | \nString/Array | \n[] | \n
onSelect | \ncallback function triggered when select or unselect menu item signatures: Function(selectedKeys: Array, item: Object, extra: Object) => void params: selectedKeys: {Array} keys of selected menu item item: {Object} current operation menu item extra: {Object} extra params extra.select: {Boolean} whether is selected extra.key: {Array} key of current operation menu item extra.label: {Object} label of current operation menu item extra.keyPath: {Array} key path of current operation menu item | \nFunction | \n() => {} | \n
selectMode | \nselect mode, single or multiple, no value by default, not selectable options: 'single', 'multiple' | \nEnum | \n- | \n
shallowSelect | \nwhether you can only select the first level menu item (you cannot select the menu item in the submenu) | \nBoolean | \nfalse | \n
hasSelectedIcon | \nwhether to show the selected icon, if it is set to false, it needs to match the background color when the configuration platform setting is selected to distinguish between | \nBoolean | \ntrue | \n
isSelectIconRight | \nwhether to set the selected icon on right side of menu, this only works when hasSelectedIcon is true Attention:select icon on SubMenu always lie on left of menu | \nBoolean | \nfalse | \n
direction | \ndirection of the menu's first level options: 'ver', 'hoz' | \nEnum | \n'ver' | \n
hozAlign | \nalignment of items and footer in the horizontal menu bar, only works when direction is set to 'hoz' and the header exists options: 'left', 'right' | \nEnum | \n'left' | \n
header | \nheader of menu | \nReactNode | \n- | \n
footer | \nfooter of menu | \nReactNode | \n- | \n
autoFocus | \nwhether to get focus automatically | \nBoolean | \nfalse | \n
focusedKey | \nkeys of the currently focused submenu or menu item | \nString | \n- | \n
embeddable | \nintegrate with the background or not(which means no background/border/box-shadow etc.), usually used with Layout. You can also custom its height like<Menu style={{lineHeight: '100px'}}> | \nBoolean | \nfalse | \n
Param | \nDescripiton | \nType | \nDefault Value | \n
---|---|---|---|
disabled | \nwhether is disabled | \nBoolean | \nfalse | \n
helper | \nhelp text | \nReactNode | \n- | \n
children | \ncontent of menu item | \nReactNode | \n- | \n
Param | \nDescripiton | \nType | \nDefault Value | \n
---|---|---|---|
label | \nlabel of submenu | \nReactNode | \n- | \n
selectable | \nwhether is selectable, it only works when set selectMode of Menu | \nBoolean | \nfalse | \n
mode | \nopen mode of submenu, it will override the property with the same name on Menu options: 'inline', 'popup' | \nEnum | \nmode fo Menu | \n
children | \nmenu item or submenu | \nReactNode | \n- | \n
Param | \nDescripiton | \nType | \nDefault Value | \n
---|---|---|---|
label | \nlabel of the parent item | \nReactNode | \n- | \n
children | \ncontent of the pop up | \nReactNode | \n- | \n
\n\nThis subcomponent selection is not controlled by defaultSelectedKeys/selectedKeys. Please control the selected yourself.
\n
Param | \nDescripiton | \nType | \nDefault Value | \n
---|---|---|---|
checked | \nwhether is checked | \nBoolean | \nfalse | \n
indeterminate | \nwhether is indeterminate | \nBoolean | \nfalse | \n
disabled | \nwhether is disabled | \nBoolean | \nfalse | \n
onChange | \ncallback function triggered when check or uncheck menu item signatures: Function(checked: Boolean, event: Object) => void params: checked: {Boolean} whether is checked event: {Object} checked event | \nFunction | \n() => {} | \n
helper | \nhelp text | \nReactNode | \n- | \n
children | \ncontent of menu check item | \nReactNode | \n- | \n
\n\nThis subcomponent selection is not controlled by defaultSelectedKeys/selectedKeys. Please control the selected yourself.
\n
Param | \nDescripiton | \nType | \nDefault Value | \n
---|---|---|---|
checked | \nwhether is checked | \nBoolean | \nfalse | \n
disabled | \nwhether is disabled | \nBoolean | \nfalse | \n
onChange | \ncallback function triggered when check or uncheck menu item signatures: Function(checked: Boolean, event: Object) => void params: checked: {Boolean} whether is checked event: {Object} checked event | \nFunction | \n() => {} | \n
helper | \nhelp text | \nReactNode | \n- | \n
children | \ncontent of menu radio item | \nReactNode | \n- | \n
Param | \nDescripiton | \nType | \nDefault Value | \n
---|---|---|---|
label | \nlabel of group | \nReactNode | \n- | \n
children | \nmenu items | \nReactNode | \n- | \n
Create a context menu.
\nKeyBoard | \nDescripiton | \n
---|---|
Up Arrow | \nnavigate to previous item | \n
Down Arrow | \nnavigate to next item | \n
Right Arrow | \nopen the submenu, navigate to the first item of the submenu; horizontal menu bar first level, navigate to the right one | \n
Left Arrow | \nclose the submenu, navigate to the parent menu; horizontal menu bar first level, navigation to the left one | \n
Enter | \nopen submenu and navigate to the first item of the submenu | \n
Esc | \nclose submenu and navigate to the parent menu item | \n
Space | \ntoggle selected or checked | \n
参数 | \n说明 | \n类型 | \n默认值 | \n
---|---|---|---|
children | \n菜单项和子菜单 | \nReactNode | \n- | \n
onItemClick | \n点击菜单项触发的回调函数 签名: Function(key: String, item: Object, event: Object) => void 参数: key: {String} 点击的菜单项的 key 值 item: {Object} 点击的菜单项对象 event: {Object} 点击的事件对象 | \nFunction | \n() => {} | \n
openKeys | \n当前打开的子菜单的 key 值 | \nString/Array | \n- | \n
defaultOpenKeys | \n初始打开的子菜单的 key 值 | \nString/Array | \n[] | \n
defaultOpenAll | \n初始展开所有的子菜单,只在 mode 设置为 'inline' 以及 openMode 设置为 'multiple' 下生效,优先级高于 defaultOpenKeys | \nBoolean | \nfalse | \n
onOpen | \n打开或关闭子菜单触发的回调函数 签名: Function(key: String, extra: Object) => void 参数: key: {String} 打开的所有子菜单的 key 值 extra: {Object} 额外参数 extra.key: {String} 当前操作子菜单的 key 值 extra.open: {Boolean} 是否是打开 | \nFunction | \n() => {} | \n
mode | \n子菜单打开的模式 可选值: 'inline', 'popup' | \nEnum | \n'inline' | \n
triggerType | \n子菜单打开的触发行为 可选值: 'click', 'hover' | \nEnum | \n'click' | \n
openMode | \n展开内连子菜单的模式,同时可以展开一个子菜单还是多个子菜单,该属性仅在 mode 为 inline 时生效 可选值: 'single', 'multiple' | \nEnum | \n'multiple' | \n
inlineIndent | \n内连子菜单缩进距离 | \nNumber | \n20 | \n
popupAutoWidth | \n是否自动让弹层的宽度和菜单项保持一致,如果弹层的宽度比菜单项小则和菜单项保持一致,如果宽度大于菜单项则不做处理 | \nBoolean | \nfalse | \n
popupAlign | \n弹层的对齐方式 可选值: 'follow', 'outside' | \nEnum | \n'follow' | \n
popupProps | \n弹层自定义 props | \nObject/Function | \n{} | \n
popupClassName | \n弹出子菜单自定义 className | \nString | \n- | \n
popupStyle | \n弹出子菜单自定义 style | \nObject | \n- | \n
selectedKeys | \n当前选中菜单项的 key 值 | \nString/Array | \n- | \n
defaultSelectedKeys | \n初始选中菜单项的 key 值 | \nString/Array | \n[] | \n
onSelect | \n选中或取消选中菜单项触发的回调函数 签名: Function(selectedKeys: Array, item: Object, extra: Object) => void 参数: selectedKeys: {Array} 选中的所有菜单项的值 item: {Object} 选中或取消选中的菜单项 extra: {Object} 额外参数 extra.select: {Boolean} 是否是选中 extra.key: {Array} 菜单项的 key extra.label: {Object} 菜单项的文本 extra.keyPath: {Array} 菜单项 key 的路径 | \nFunction | \n() => {} | \n
selectMode | \n选中模式,单选还是多选,默认无值,不可选 可选值: 'single', 'multiple' | \nEnum | \n- | \n
shallowSelect | \n是否只能选择第一层菜单项(不能选择子菜单中的菜单项) | \nBoolean | \nfalse | \n
hasSelectedIcon | \n是否显示选中图标,如果设置为 false 需配合配置平台设置选中时的背景色以示区分 | \nBoolean | \ntrue | \n
isSelectIconRight | \n是否将选中图标居右,仅当 hasSelectedIcon 为true 时生效。 注意:SubMenu 上的选中图标一直居左,不受此API控制 | \nBoolean | \nfalse | \n
direction | \n菜单第一层展示方向 可选值: 'ver', 'hoz' | \nEnum | \n'ver' | \n
hozAlign | \n横向菜单条 item 和 footer 的对齐方向,在 direction 设置为 'hoz' 并且 header 存在时生效 可选值: 'left', 'right' | \nEnum | \n'left' | \n
hozInLine | \n横向菜单模式下,是否维持在一行,即超出一行折叠成 SubMenu 显示, 仅在 direction='hoz' mode='popup' 时生效 | \nBoolean | \nfalse | \n
header | \n自定义菜单头部 | \nReactNode | \n- | \n
footer | \n自定义菜单尾部 | \nReactNode | \n- | \n
autoFocus | \n是否自动获得焦点 | \nBoolean | \nfalse | \n
focusedKey | \n当前获得焦点的子菜单或菜单项 key 值 | \nString | \n- | \n
embeddable | \n是否开启嵌入式模式,一般用于Layout的布局中,开启后没有默认背景、外层border、box-shadow,可以配合<Menu style={{lineHeight: '100px'}}> 自定义高度 | \nBoolean | \nfalse | \n
参数 | \n说明 | \n类型 | \n默认值 | \n
---|---|---|---|
disabled | \n是否禁用 | \nBoolean | \nfalse | \n
helper | \n帮助文本 | \nReactNode | \n- | \n
children | \n菜单项标签内容 | \nReactNode | \n- | \n
参数 | \n说明 | \n类型 | \n默认值 | \n
---|---|---|---|
label | \n标签内容 | \nReactNode | \n- | \n
selectable | \n是否可选,该属性仅在设置 Menu 组件 selectMode 属性后生效 | \nBoolean | \nfalse | \n
mode | \n子菜单打开方式,如果设置会覆盖 Menu 上的同名属性 可选值: 'inline', 'popup' | \nEnum | \nMenu 的 mode 属性值 | \n
children | \n菜单项或下一级子菜单 | \nReactNode | \n- | \n
参数 | \n说明 | \n类型 | \n默认值 | \n
---|---|---|---|
label | \n标签内容 | \nReactNode | \n- | \n
children | \n自定义弹层内容 | \nReactNode | \n- | \n
\n\n该子组件选中情况不受 defaultSelectedKeys/selectedKeys 控制,请自行控制选中逻辑
\n
参数 | \n说明 | \n类型 | \n默认值 | \n
---|---|---|---|
checked | \n是否选中 | \nBoolean | \nfalse | \n
indeterminate | \n是否半选中 | \nBoolean | \nfalse | \n
disabled | \n是否禁用 | \nBoolean | \nfalse | \n
onChange | \n选中或取消选中触发的回调函数 签名: Function(checked: Boolean, event: Object) => void 参数: checked: {Boolean} 是否选中 event: {Object} 选中事件对象 | \nFunction | \n() => {} | \n
helper | \n帮助文本 | \nReactNode | \n- | \n
children | \n标签内容 | \nReactNode | \n- | \n
\n\n该子组件选中情况不受 defaultSelectedKeys/selectedKeys 控制,请自行控制选中逻辑
\n
参数 | \n说明 | \n类型 | \n默认值 | \n
---|---|---|---|
checked | \n是否选中 | \nBoolean | \nfalse | \n
disabled | \n是否禁用 | \nBoolean | \nfalse | \n
onChange | \n选中或取消选中触发的回调函数 签名: Function(checked: Boolean, event: Object) => void 参数: checked: {Boolean} 是否选中 event: {Object} 选中事件对象 | \nFunction | \n() => {} | \n
helper | \n帮助文本 | \nReactNode | \n- | \n
children | \n标签内容 | \nReactNode | \n- | \n
参数 | \n说明 | \n类型 | \n默认值 | \n
---|---|---|---|
label | \n标签内容 | \nReactNode | \n- | \n
children | \n菜单项 | \nReactNode | \n- | \n
创建上下文菜单。
\n按键 | \n说明 | \n
---|---|
Up Arrow | \n导航到上一项 | \n
Down Arrow | \n导航到下一项 | \n
Right Arrow | \n打开子菜单,导航到子菜单第一项;横向菜单条第一层,导航到右一项 | \n
Left Arrow | \n关闭子菜单,导航到父级菜单;横向菜单条第一层,导航都左一项 | \n
Enter | \n打开子菜单,导航到子菜单第一项 | \n
Esc | \n关闭子菜单,导航到父级菜单 | \n
SPACE | \n切换选中状态 | \n
When you click button
through the Enter key, it automatically focuses on Message
to read the information.Please refer to ARIA and KeyBoard
.
import { Message, Button } from '@alifd/next';\n\nconst showSuccess = () => Message.success('success');\nReactDOM.render(\n <div className=\"message-toast-quick-demo\">\n <Button onClick={showSuccess}>success</Button>\n </div>, mountNode);\n
通过Enter键点击button
时,自动聚焦到Message
上读取信息。请参考ARIA and KeyBoard
。
import { Message, Button } from '@alifd/next';\n\nconst showSuccess = () => Message.success('success');\nReactDOM.render(\n <div className=\"message-toast-quick-demo\">\n <Button onClick={showSuccess}>success</Button>\n </div>, mountNode);\n
import { Message, Button } from '@alifd/next';\n\nclass App extends React.Component {\n state = {\n visible: true\n }\n\n handleChange = () => {\n this.setState({\n visible: !this.state.visible\n });\n }\n\n handleClose = () => {\n this.setState({\n visible: false\n });\n }\n\n render() {\n const { visible } = this.state;\n\n return (\n <div className=\"control-demo\">\n <Button onClick={this.handleChange}>Toggle Visible</Button>\n <Message type=\"warning\" visible={visible} title=\"Warning\" closeable onClose={this.handleClose}>\n This item already has the label \"travel\". You can add a new label.\n </Message>\n </div>\n );\n }\n}\n\nReactDOM.render(<App />, mountNode);
.control-demo .next-btn.next-medium {\n margin-bottom: 10px;\n}
import { Message, Button } from '@alifd/next';\n\nclass App extends React.Component {\n state = {\n visible: true\n }\n\n handleChange = () => {\n this.setState({\n visible: !this.state.visible\n });\n }\n\n handleClose = () => {\n this.setState({\n visible: false\n });\n }\n\n render() {\n const { visible } = this.state;\n\n return (\n <div className=\"control-demo\">\n <Button onClick={this.handleChange}>Toggle Visible</Button>\n <Message type=\"warning\" visible={visible} title=\"Warning\" closeable onClose={this.handleClose}>\n This item already has the label \"travel\". You can add a new label.\n </Message>\n </div>\n );\n }\n}\n\nReactDOM.render(<App />, mountNode);
.control-demo .next-btn.next-medium {\n margin-bottom: 10px;\n}
You can control whether the message can be closed by adding the closeable
property.
import { Message } from '@alifd/next';\n\nconst onClose = () => console.log('onClose triggered!');\nconst afterClose = () => console.log('afterClose triggered!');\n\nReactDOM.render(\n <div>\n <Message title=\"title\" closeable onClose={onClose} afterClose={afterClose}>\n Content Content Content Content\n </Message>\n </div>, mountNode);
通过增加closeable
属性可以控制提示框是否可关闭。
import { Message } from '@alifd/next';\n\nconst onClose = () => console.log('onClose triggered!');\nconst afterClose = () => console.log('afterClose triggered!');\n\nReactDOM.render(\n <div>\n <Message title=\"title\" closeable onClose={onClose} afterClose={afterClose}>\n Content Content Content Content\n </Message>\n </div>, mountNode);
You can control the shape of message by setting the shape
property.
import { Message, Radio } from '@alifd/next';\n\nconst types = ['success', 'warning', 'error', 'notice', 'help', 'loading'];\nconst list = [\n {\n value: 'inline',\n label: 'inline'\n }, {\n value: 'addon',\n label: 'addon'\n }, {\n value: 'toast',\n label: 'toast'\n }\n];\n\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n this.state = {\n shape: 'inline'\n };\n this.handleSelect = this.handleSelect.bind(this);\n }\n\n handleSelect(shape) {\n this.setState({ shape });\n }\n\n render() {\n const { shape } = this.state;\n\n return (\n <div className=\"message-shape-demo\">\n <span className=\"demo-label\">Select Shape:</span>\n <Radio.Group defaultValue=\"inline\" dataSource={list} value={this.state.shape} onChange={this.handleSelect} />\n\n\n {types.map(type => (\n <Message key={type} title={type} type={type} shape={shape}>\n Content Content Content Content\n </Message>\n ))}\n </div>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
.message-shape-demo .demo-label {\n display: inline-block;\n vertical-align: top;\n height: 22px;\n line-height: 22px;\n}\n\n.message-shape-demo .next-message-title {\n text-transform: capitalize;\n}\n\n.message-shape-demo .next-message {\n margin-top: 10px;\n}\n\n.message-shape-demo .next-message.next-message-toast {\n position: relative !important;\n}
通过设置shape
调整信息外观
import { Message, Radio } from '@alifd/next';\n\nconst types = ['success', 'warning', 'error', 'notice', 'help', 'loading'];\nconst list = [\n {\n value: 'inline',\n label: 'inline'\n }, {\n value: 'addon',\n label: 'addon'\n }, {\n value: 'toast',\n label: 'toast'\n }\n];\n\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n this.state = {\n shape: 'inline'\n };\n this.handleSelect = this.handleSelect.bind(this);\n }\n\n handleSelect(shape) {\n this.setState({ shape });\n }\n\n render() {\n const { shape } = this.state;\n\n return (\n <div className=\"message-shape-demo\">\n <span className=\"demo-label\">Select Shape:</span>\n <Radio.Group defaultValue=\"inline\" dataSource={list} value={this.state.shape} onChange={this.handleSelect} />\n\n\n {types.map(type => (\n <Message key={type} title={type} type={type} shape={shape}>\n Content Content Content Content\n </Message>\n ))}\n </div>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
.message-shape-demo .demo-label {\n display: inline-block;\n vertical-align: top;\n height: 22px;\n line-height: 22px;\n}\n\n.message-shape-demo .next-message-title {\n text-transform: capitalize;\n}\n\n.message-shape-demo .next-message {\n margin-top: 10px;\n}\n\n.message-shape-demo .next-message.next-message-toast {\n position: relative !important;\n}
You can control the size of message by setting the size
property.
import { Message, Radio } from '@alifd/next';\n\nconst types = ['success', 'warning', 'error', 'notice', 'help', 'loading'];\nconst list = [\n {\n value: 'medium',\n label: 'medium'\n }, {\n value: 'large',\n label: 'large'\n }\n];\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n this.state = {\n size: 'medium'\n };\n this.handleSelect = this.handleSelect.bind(this);\n }\n\n handleSelect(size) {\n this.setState({ size });\n }\n\n render() {\n const { size } = this.state;\n\n return (\n <div className=\"message-size-demo\">\n <span className=\"demo-label\">Select Size:</span>\n <Radio.Group defaultValue=\"medium\" dataSource={list} value={this.state.size} onChange={this.handleSelect} />\n\n {types.map(type => (\n <Message key={type} title={type} type={type} size={size}>\n Content Content Content Content\n </Message>\n ))}\n </div>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
.message-size-demo .demo-label {\n display: inline-block;\n vertical-align: top;\n height: 28px;\n line-height: 28px;\n}\n\n.message-size-demo .next-message-title {\n text-transform: capitalize;\n}\n\n.message-size-demo .next-message {\n margin-top: 10px;\n}
通过size
设置尺寸
import { Message, Radio } from '@alifd/next';\n\nconst types = ['success', 'warning', 'error', 'notice', 'help', 'loading'];\nconst list = [\n {\n value: 'medium',\n label: 'medium'\n }, {\n value: 'large',\n label: 'large'\n }\n];\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n this.state = {\n size: 'medium'\n };\n this.handleSelect = this.handleSelect.bind(this);\n }\n\n handleSelect(size) {\n this.setState({ size });\n }\n\n render() {\n const { size } = this.state;\n\n return (\n <div className=\"message-size-demo\">\n <span className=\"demo-label\">Select Size:</span>\n <Radio.Group defaultValue=\"medium\" dataSource={list} value={this.state.size} onChange={this.handleSelect} />\n\n {types.map(type => (\n <Message key={type} title={type} type={type} size={size}>\n Content Content Content Content\n </Message>\n ))}\n </div>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
.message-size-demo .demo-label {\n display: inline-block;\n vertical-align: top;\n height: 28px;\n line-height: 28px;\n}\n\n.message-size-demo .next-message-title {\n text-transform: capitalize;\n}\n\n.message-size-demo .next-message {\n margin-top: 10px;\n}
You can use static method such as Message.success
to show the specified type toast.
import { Message, Button } from '@alifd/next';\n\n\nconst showSuccess = () => Message.success('success');\nconst showWarning = () => Message.warning('warning');\nconst showError = () => Message.error('error');\nconst showNotice = () => Message.notice('notice');\nconst showHelp = () => Message.help('help');\nconst showLoading = () => Message.loading('loading');\n\nReactDOM.render(\n <div className=\"message-toast-quick-demo\">\n <Button onClick={showSuccess}>success</Button>\n <Button onClick={showWarning}>warning</Button>\n <Button onClick={showError}>error</Button>\n <Button onClick={showNotice}>notice</Button>\n <Button onClick={showHelp}>help</Button>\n <Button onClick={showLoading}>loading</Button>\n </div>, mountNode);
.message-toast-quick-demo .next-btn.next-medium {\n margin-right: 10px;\n margin-bottom: 10px;\n}
可以通过Message.success
等静态方法来方便的显示指定类型的信息弹窗。
import { Message, Button } from '@alifd/next';\n\n\nconst showSuccess = () => Message.success('success');\nconst showWarning = () => Message.warning('warning');\nconst showError = () => Message.error('error');\nconst showNotice = () => Message.notice('notice');\nconst showHelp = () => Message.help('help');\nconst showLoading = () => Message.loading('loading');\n\nReactDOM.render(\n <div className=\"message-toast-quick-demo\">\n <Button onClick={showSuccess}>success</Button>\n <Button onClick={showWarning}>warning</Button>\n <Button onClick={showError}>error</Button>\n <Button onClick={showNotice}>notice</Button>\n <Button onClick={showHelp}>help</Button>\n <Button onClick={showLoading}>loading</Button>\n </div>, mountNode);
.message-toast-quick-demo .next-btn.next-medium {\n margin-right: 10px;\n margin-bottom: 10px;\n}
You can use Message.show
and Message.hide
to show and hide toast conveniently.
import { Message, Button } from '@alifd/next';\n\n\nconst show = () => {\n Message.show({\n type: 'loading',\n content: 'Will be closed after 3 seconds or manually click on the close button',\n afterClose: () => console.log('Closed the toast')\n });\n};\nconst hide = () => Message.hide();\n\nReactDOM.render(\n <div className=\"message-toast-demo\">\n <Button onClick={show}>Show</Button>\n <Button onClick={hide}>Hide</Button>\n </div>, mountNode);
.message-toast-demo .next-btn.next-medium {\n margin-right: 10px;\n}
可以通过Message.show
和Message.hide
方法来方便的显示或隐藏反馈弹窗。
import { Message, Button } from '@alifd/next';\n\n\nconst show = () => {\n Message.show({\n type: 'loading',\n content: 'Will be closed after 3 seconds or manually click on the close button',\n afterClose: () => console.log('Closed the toast')\n });\n};\nconst hide = () => Message.hide();\n\nReactDOM.render(\n <div className=\"message-toast-demo\">\n <Button onClick={show}>Show</Button>\n <Button onClick={hide}>Hide</Button>\n </div>, mountNode);
.message-toast-demo .next-btn.next-medium {\n margin-right: 10px;\n}
You can control the type of message by setting the type
property.
import { Message } from '@alifd/next';\n\nReactDOM.render(\n <div className=\"message-type-demo\">\n <Message title=\"Success\" type=\"success\">\n Content Content Content Content\n </Message>\n <Message title=\"Warning\" type=\"warning\">\n Content Content Content Content\n </Message>\n <Message title=\"Error\" type=\"error\">\n Content Content Content Content\n </Message>\n <Message title=\"Notice\" type=\"notice\">\n Content Content Content Content\n </Message>\n <Message title=\"Help\" type=\"help\">\n Content Content Content Content\n </Message>\n <Message title=\"Loading\" type=\"loading\">\n Content Content Content Content\n </Message>\n </div>, mountNode);
.message-type-demo .next-message {\n margin-bottom: 10px;\n}
通过设置type
调整信息类型
import { Message } from '@alifd/next';\n\nReactDOM.render(\n <div className=\"message-type-demo\">\n <Message title=\"Success\" type=\"success\">\n Content Content Content Content\n </Message>\n <Message title=\"Warning\" type=\"warning\">\n Content Content Content Content\n </Message>\n <Message title=\"Error\" type=\"error\">\n Content Content Content Content\n </Message>\n <Message title=\"Notice\" type=\"notice\">\n Content Content Content Content\n </Message>\n <Message title=\"Help\" type=\"help\">\n Content Content Content Content\n </Message>\n <Message title=\"Loading\" type=\"loading\">\n Content Content Content Content\n </Message>\n </div>, mountNode);
.message-type-demo .next-message {\n margin-bottom: 10px;\n}
Param | \nDescripiton | \nType | \nDefault Value | \n
---|---|---|---|
size | \nsize of message option: 'medium', 'large' | \nEnum | \n'medium' | \n
type | \ntype of message option: 'success', 'warning', 'error', 'notice', 'help', 'loading' | \nEnum | \n'success' | \n
shape | \nshape of message option: 'inline', 'addon', 'toast' | \nEnum | \n'inline' | \n
title | \ntitle of message | \nReactNode | \n- | \n
children | \ncontent of message | \nReactNode | \n- | \n
defaultVisible | \nwhether the message is visible in default | \nBoolean | \ntrue | \n
visible | \nwhether the message is visible currently | \nBoolean | \n- | \n
iconType | \ntype of icon, overriding the internally type of icon | \nString | \n- | \n
closeable | \nwhether to show the close button | \nBoolean | \nfalse | \n
onClose | \ncallback function triggered when close signatures: Function() => void | \nFunction | \n() => {} | \n
afterClose | \ncallback function triggered after closed signatures: Function() => void | \nFunction | \n() => {} | \n
animation | \nwhether to enable expand and collapse animation | \nBoolean | \ntrue | \n
Message.show(props)
provides a singleton call with the following configuration parameters (inheriting Overlay
configuration):
Param | \nDescripiton | \nType | \nDefault Value | \n
---|---|---|---|
type | \ntype of message | \nString | \n'success' | \n
title | \ntitle of message | \nReactNode | \n- | \n
content | \ncontent of message | \nReactNode | \n- | \n
duration | \nshow duration, 0 means always present, in milliseconds | \nNumber | \n3000 | \n
align | \nalignment reference Overlay | \nString | \n'tc tc' | \n
offset | \noffset after positioned | \nArray | \n[0, 0] | \n
hasMask | \nwhether to have a mask | \nBoolean | \nfalse | \n
closeable | \nwhether to show the close button | \nBoolean | \nfalse | \n
afterClose | \ncallback function triggered after closed | \nFunction | \n- | \n
overlayProps | \nprops of Overlay | \nObject | \n- | \n
Example:
\nMessage.show({\n type: 'error',\n title: 'Error',\n content: 'Please contact admin feedback!',\n hasMask: true\n});
Message.hide()
provides a quick way to close the message.
Quick ways of Message.show({type: type, title: 'xxx'});
.
Example:
\nMessage.success('message content');\n\n// or\nMessage.success({\n title: 'message content',\n duration: 1000\n});
Description
: This component needs to be used in conjunction with other components to be prompted. Refer to the above accessibility
参数 | \n说明 | \n类型 | \n默认值 | \n
---|---|---|---|
size | \n反馈大小 可选值: 'medium', 'large' | \nEnum | \n'medium' | \n
type | \n反馈类型 可选值: 'success', 'warning', 'error', 'notice', 'help', 'loading' | \nEnum | \n'success' | \n
shape | \n反馈外观 可选值: 'inline', 'addon', 'toast' | \nEnum | \n'inline' | \n
title | \n标题 | \nReactNode | \n- | \n
children | \n内容 | \nReactNode | \n- | \n
defaultVisible | \n默认是否显示 | \nBoolean | \ntrue | \n
visible | \n当前是否显示 | \nBoolean | \n- | \n
iconType | \n显示的图标类型,会覆盖内部设置的IconType | \nString | \n- | \n
closeable | \n显示关闭按钮 | \nBoolean | \nfalse | \n
onClose | \n关闭按钮的回调 签名: Function() => void | \nFunction | \n() => {} | \n
afterClose | \n关闭之后调用的函数 签名: Function() => void | \nFunction | \n() => {} | \n
animation | \n是否开启展开收起动画 | \nBoolean | \ntrue | \n
Message.show(props)
提供一个单例的调用方式,配置参数如下(继承 Overlay
的配置):
参数 | \n说明 | \n类型 | \n默认值 | \n
---|---|---|---|
type | \n反馈类型 | \nString | \n'success' | \n
title | \n反馈标题 | \nReactNode | \n- | \n
content | \n反馈内容 | \nReactNode | \n- | \n
duration | \n显示持续时间,0表示一直存在,以毫秒为单位 | \nNumber | \n3000 | \n
align | \n对齐方式,参考Overlay | \nString | \n'tc tc' | \n
offset | \n对齐之后的偏移位置 | \nArray | \n[0, 0] | \n
hasMask | \n是否带有遮罩 | \nBoolean | \nfalse | \n
closeable | \n显示关闭按钮 | \nBoolean | \nfalse | \n
afterClose | \n关闭事件的回调函数 | \nFunction | \n- | \n
overlayProps | \n透传到弹层的属性对象 | \nObject | \n- | \n
示例:
\nMessage.show({\n type: 'error',\n title: '错误',\n content: '请联系相关人员反馈!',\n hasMask: true\n});
Message.hide()
提供关闭反馈弹层的快捷方法。
Message.show({type: type, title: 'xxx'});
的便捷调用方法。
示例:
\nMessage.success('反馈内容');\n\n// 或者\nMessage.success({\n title: '反馈内容',\n duration: 1000\n});
说明
: 此组件需要结合其他组件使用,才会有提示。参考上文无障碍
。
The simplest way to use it.
\n","order":"0"},"codes":{"jsx":"import { Nav } from '@alifd/next';\n\n\nconst { Item, SubNav } = Nav;\n\nconst header = FUSION;\nconst footer = Login in;\n\nReactDOM.render(\n \n , mountNode);\n","css":".basic-nav .fusion {\n margin: 8px 20px;\n width: 100px;\n color: #FFFFFF;\n font-size: 20px;\n}\n.basic-nav .login-in {\n margin: 0 20px;\n color: #FFFFFF;\n}\n.basic-nav .next-nav-item {\n width: 120px;\n}\n"},"body":"\n````jsx\nimport { Nav } from '@alifd/next';\n\n\nconst { Item, SubNav } = Nav;\n\nconst header = FUSION;\nconst footer = Login in;\n\nReactDOM.render(\n \n , mountNode);\n````\n\n````css\n.basic-nav .fusion {\n margin: 8px 20px;\n width: 100px;\n color: #FFFFFF;\n font-size: 20px;\n}\n.basic-nav .login-in {\n margin: 0 20px;\n color: #FFFFFF;\n}\n.basic-nav .next-nav-item {\n width: 120px;\n}\n````","html":"import { Nav } from '@alifd/next';\n\n\nconst { Item, SubNav } = Nav;\n\nconst header = <span className=\"fusion\">FUSION</span>;\nconst footer = <a className=\"login-in\" href=\"javascript:;\">Login in</a>;\n\nReactDOM.render(\n <Nav className=\"basic-nav\" direction=\"hoz\" type=\"primary\" header={header} footer={footer} defaultSelectedKeys={['home']} triggerType=\"hover\">\n <Item key=\"home\">Home</Item>\n <SubNav label=\"Component\" selectable>\n <Item key=\"next\">Next</Item>\n <Item key=\"mext\">Mext</Item>\n </SubNav>\n <Item key=\"document\">Document</Item>\n </Nav>\n , mountNode);
.basic-nav .fusion {\n margin: 8px 20px;\n width: 100px;\n color: #FFFFFF;\n font-size: 20px;\n}\n.basic-nav .login-in {\n margin: 0 20px;\n color: #FFFFFF;\n}\n.basic-nav .next-nav-item {\n width: 120px;\n}
最简单的使用方式。
\n","order":"0"},"codes":{"jsx":"import { Nav } from '@alifd/next';\n\n\nconst { Item, SubNav } = Nav;\n\nconst header = FUSION;\nconst footer = Login in;\n\nReactDOM.render(\n \n , mountNode);\n","css":".basic-nav .fusion {\n margin: 8px 20px;\n width: 100px;\n color: #FFFFFF;\n font-size: 20px;\n}\n.basic-nav .login-in {\n margin: 0 20px;\n color: #FFFFFF;\n}\n.basic-nav .next-nav-item {\n width: 120px;\n}\n"},"body":"\n\n````jsx\nimport { Nav } from '@alifd/next';\n\n\nconst { Item, SubNav } = Nav;\n\nconst header = FUSION;\nconst footer = Login in;\n\nReactDOM.render(\n \n , mountNode);\n````\n\n````css\n.basic-nav .fusion {\n margin: 8px 20px;\n width: 100px;\n color: #FFFFFF;\n font-size: 20px;\n}\n.basic-nav .login-in {\n margin: 0 20px;\n color: #FFFFFF;\n}\n.basic-nav .next-nav-item {\n width: 120px;\n}\n````","html":"import { Nav } from '@alifd/next';\n\n\nconst { Item, SubNav } = Nav;\n\nconst header = <span className=\"fusion\">FUSION</span>;\nconst footer = <a className=\"login-in\" href=\"javascript:;\">Login in</a>;\n\nReactDOM.render(\n <Nav className=\"basic-nav\" direction=\"hoz\" type=\"primary\" header={header} footer={footer} defaultSelectedKeys={['home']} triggerType=\"hover\">\n <Item key=\"home\">Home</Item>\n <SubNav label=\"Component\" selectable>\n <Item key=\"next\">Next</Item>\n <Item key=\"mext\">Mext</Item>\n </SubNav>\n <Item key=\"document\">Document</Item>\n </Nav>\n , mountNode);
.basic-nav .fusion {\n margin: 8px 20px;\n width: 100px;\n color: #FFFFFF;\n font-size: 20px;\n}\n.basic-nav .login-in {\n margin: 0 20px;\n color: #FFFFFF;\n}\n.basic-nav .next-nav-item {\n width: 120px;\n}
Nav provides a lot of configurations that can be personalized.
\n","order":"1"},"codes":{"jsx":"import { Nav, Radio } from '@alifd/next';\n\n\nconst { Item, SubNav } = Nav;\n\nclass App extends React.Component {\n state = {\n type: 'normal',\n direction: 'hoz',\n activeDirection: null,\n triggerType: 'click'\n }\n\n setValue(name, value) {\n this.setState({\n [name]: value === '' ? null : value\n });\n }\n\n setTriggerType(triggerType) {\n this.setState({\n triggerType\n });\n }\n\n render() {\n const { type, direction, activeDirection, triggerType } = this.state;\n\n return (\nimport { Nav, Radio } from '@alifd/next';\n\n\nconst { Item, SubNav } = Nav;\n\nclass App extends React.Component {\n state = {\n type: 'normal',\n direction: 'hoz',\n activeDirection: null,\n triggerType: 'click'\n }\n\n setValue(name, value) {\n this.setState({\n [name]: value === '' ? null : value\n });\n }\n\n setTriggerType(triggerType) {\n this.setState({\n triggerType\n });\n }\n\n render() {\n const { type, direction, activeDirection, triggerType } = this.state;\n\n return (\n <div>\n <div className=\"demo-ctl\">\n <Radio.Group shape=\"button\" size=\"medium\" value={type} onChange={this.setValue.bind(this, 'type')}>\n <Radio value=\"normal\">type=\"normal\"</Radio>\n <Radio value=\"primary\">type=\"primary\"</Radio>\n <Radio value=\"secondary\">type=\"secondary\"</Radio>\n <Radio value=\"line\">type=\"line\"</Radio>\n </Radio.Group>\n <Radio.Group shape=\"button\" size=\"medium\" value={direction} onChange={this.setValue.bind(this, 'direction')}>\n <Radio value=\"hoz\">direction=\"hoz\"</Radio>\n <Radio value=\"ver\">direction=\"ver\"</Radio>\n </Radio.Group>\n <Radio.Group shape=\"button\" size=\"medium\" value={activeDirection === null ? '' : activeDirection} onChange={this.setValue.bind(this, 'activeDirection')}>\n <Radio value=\"\">activeDirection=null</Radio>\n {direction === 'hoz' ? <Radio value=\"top\">activeDirection=\"top\"</Radio> : null}\n {direction === 'hoz' ? <Radio value=\"bottom\">activeDirection=\"bottom\"</Radio> : null}\n {direction === 'ver' ? <Radio value=\"left\">activeDirection=\"left\"</Radio> : null}\n {direction === 'ver' ? <Radio value=\"right\">activeDirection=\"right\"</Radio> : null}\n </Radio.Group>\n <Radio.Group shape=\"button\" size=\"medium\" value={triggerType} onChange={this.setTriggerType.bind(this)}>\n <Radio value=\"click\">triggerType=\"click\"</Radio>\n <Radio value=\"hover\">triggerType=\"hover\"</Radio>\n </Radio.Group>\n </div>\n <Nav className=\"custom-nav\" type={type} direction={direction} activeDirection={activeDirection} triggerType={triggerType}>\n <Item>Item 1</Item>\n <Item>Item 2</Item>\n <SubNav label=\"Sub Nav\">\n <Item>Item 3</Item>\n <Item>Item 4</Item>\n <SubNav label=\"Sub Nav\">\n <Item>Item 5</Item>\n <Item>Item 6</Item>\n </SubNav>\n </SubNav>\n <Item icon=\"account\">\n <a href=\"http://www.taobao.com\" target=\"_blank\">Taobao</a>\n </Item>\n </Nav>\n </div>\n );\n }\n}\n\nReactDOM.render(<App />, mountNode);
.demo-ctl {\n background-color: #F1F1F1;\n border-left: 4px solid #0D599A;\n color: #0A7AC3;\n margin-bottom: 20px;\n padding: 5px;\n}\n.demo-ctl .next-radio-group {\n display: block;\n margin: 5px;\n}\n.custom-nav.next-hoz .next-nav-item {\n width: 100px;\n}\n.custom-nav.next-ver {\n width: 200px;\n}
Nav 提供了丰富的配置,可以进行个性化定制。
\n","order":"1"},"codes":{"jsx":"import { Nav, Radio } from '@alifd/next';\n\n\nconst { Item, SubNav } = Nav;\n\nclass App extends React.Component {\n state = {\n type: 'normal',\n direction: 'hoz',\n activeDirection: null,\n triggerType: 'click'\n }\n\n setValue(name, value) {\n this.setState({\n [name]: value === '' ? null : value\n });\n }\n\n setTriggerType(triggerType) {\n this.setState({\n triggerType\n });\n }\n\n render() {\n const { type, direction, activeDirection, triggerType } = this.state;\n\n return (\nimport { Nav, Radio } from '@alifd/next';\n\n\nconst { Item, SubNav } = Nav;\n\nclass App extends React.Component {\n state = {\n type: 'normal',\n direction: 'hoz',\n activeDirection: null,\n triggerType: 'click'\n }\n\n setValue(name, value) {\n this.setState({\n [name]: value === '' ? null : value\n });\n }\n\n setTriggerType(triggerType) {\n this.setState({\n triggerType\n });\n }\n\n render() {\n const { type, direction, activeDirection, triggerType } = this.state;\n\n return (\n <div>\n <div className=\"demo-ctl\">\n <Radio.Group shape=\"button\" size=\"medium\" value={type} onChange={this.setValue.bind(this, 'type')}>\n <Radio value=\"normal\">type=\"normal\"</Radio>\n <Radio value=\"primary\">type=\"primary\"</Radio>\n <Radio value=\"secondary\">type=\"secondary\"</Radio>\n <Radio value=\"line\">type=\"line\"</Radio>\n </Radio.Group>\n <Radio.Group shape=\"button\" size=\"medium\" value={direction} onChange={this.setValue.bind(this, 'direction')}>\n <Radio value=\"hoz\">direction=\"hoz\"</Radio>\n <Radio value=\"ver\">direction=\"ver\"</Radio>\n </Radio.Group>\n <Radio.Group shape=\"button\" size=\"medium\" value={activeDirection === null ? '' : activeDirection} onChange={this.setValue.bind(this, 'activeDirection')}>\n <Radio value=\"\">activeDirection=null</Radio>\n {direction === 'hoz' ? <Radio value=\"top\">activeDirection=\"top\"</Radio> : null}\n {direction === 'hoz' ? <Radio value=\"bottom\">activeDirection=\"bottom\"</Radio> : null}\n {direction === 'ver' ? <Radio value=\"left\">activeDirection=\"left\"</Radio> : null}\n {direction === 'ver' ? <Radio value=\"right\">activeDirection=\"right\"</Radio> : null}\n </Radio.Group>\n <Radio.Group shape=\"button\" size=\"medium\" value={triggerType} onChange={this.setTriggerType.bind(this)}>\n <Radio value=\"click\">triggerType=\"click\"</Radio>\n <Radio value=\"hover\">triggerType=\"hover\"</Radio>\n </Radio.Group>\n </div>\n <Nav className=\"custom-nav\" type={type} direction={direction} activeDirection={activeDirection} triggerType={triggerType}>\n <Item>Item 1</Item>\n <Item>Item 2</Item>\n <SubNav label=\"Sub Nav\">\n <Item>Item 3</Item>\n <Item>Item 4</Item>\n <SubNav label=\"Sub Nav\">\n <Item>Item 5</Item>\n <Item>Item 6</Item>\n </SubNav>\n </SubNav>\n <Item icon=\"account\">\n <a href=\"http://www.taobao.com\" target=\"_blank\">Taobao</a>\n </Item>\n </Nav>\n </div>\n );\n }\n}\n\nReactDOM.render(<App />, mountNode);
.demo-ctl {\n background-color: #F1F1F1;\n border-left: 4px solid #0D599A;\n color: #0A7AC3;\n margin-bottom: 20px;\n padding: 5px;\n}\n.demo-ctl .next-radio-group {\n display: block;\n margin: 5px;\n}\n.custom-nav.next-hoz .next-nav-item {\n width: 100px;\n}\n.custom-nav.next-ver {\n width: 200px;\n}
Nav could set the iconOnly property to reduce the footprint.
\n","order":"3"},"codes":{"jsx":"import { Nav } from '@alifd/next';\n\nconst { Item, Group } = Nav;\n\nReactDOM.render(\n , mountNode);\n"},"body":"\n````jsx\nimport { Nav } from '@alifd/next';\n\nconst { Item, Group } = Nav;\n\nReactDOM.render(\n , mountNode);\n````","html":"import { Nav } from '@alifd/next';\n\nconst { Item, Group } = Nav;\n\nReactDOM.render(\n <Nav style={{ width: 240 }}>\n <Group label=\"Group Label 1\">\n <Item icon=\"account\">Navigation One</Item>\n <Item icon=\"account\">Navigation Two</Item>\n <Item icon=\"account\">Navigation Three</Item>\n </Group>\n <Group label=\"Group Label 2\">\n <Item icon=\"account\">Navigation Four</Item>\n <Item icon=\"account\">Navigation Five</Item>\n <Item icon=\"account\">Navigation Six</Item>\n </Group>\n </Nav>, mountNode);
建议只在垂直布局中使用。
\n","order":"3"},"codes":{"jsx":"import { Nav } from '@alifd/next';\n\nconst { Item, Group } = Nav;\n\nReactDOM.render(\n , mountNode);\n"},"body":"\n\n````jsx\nimport { Nav } from '@alifd/next';\n\nconst { Item, Group } = Nav;\n\nReactDOM.render(\n , mountNode);\n````","html":"import { Nav } from '@alifd/next';\n\nconst { Item, Group } = Nav;\n\nReactDOM.render(\n <Nav style={{ width: 240 }}>\n <Group label=\"Group Label 1\">\n <Item icon=\"account\">Navigation One</Item>\n <Item icon=\"account\">Navigation Two</Item>\n <Item icon=\"account\">Navigation Three</Item>\n </Group>\n <Group label=\"Group Label 2\">\n <Item icon=\"account\">Navigation Four</Item>\n <Item icon=\"account\">Navigation Five</Item>\n <Item icon=\"account\">Navigation Six</Item>\n </Group>\n </Nav>, mountNode);
Nav could set the iconOnly property to reduce the footprint.
\n","order":"2"},"codes":{"jsx":"import { Nav, Radio } from '@alifd/next';\n\n\nconst { Item, SubNav } = Nav;\n\nclass App extends React.Component {\n state = {\n iconOnly: false,\n hasTooltip: true,\n hasArrow: true\n }\n\n setValue(name, value) {\n this.setState({\n [name]: value === 'true'\n });\n }\n\n render() {\n const { iconOnly, hasTooltip, hasArrow } = this.state;\n\n return (\nimport { Nav, Radio } from '@alifd/next';\n\n\nconst { Item, SubNav } = Nav;\n\nclass App extends React.Component {\n state = {\n iconOnly: false,\n hasTooltip: true,\n hasArrow: true\n }\n\n setValue(name, value) {\n this.setState({\n [name]: value === 'true'\n });\n }\n\n render() {\n const { iconOnly, hasTooltip, hasArrow } = this.state;\n\n return (\n <div>\n <div className=\"demo-ctl\">\n <Radio.Group shape=\"button\" size=\"medium\" value={iconOnly ? 'true' : 'false'} onChange={this.setValue.bind(this, 'iconOnly')}>\n <Radio value=\"true\">iconOnly=true</Radio>\n <Radio value=\"false\">iconOnly=false</Radio>\n </Radio.Group>\n {iconOnly ?\n <Radio.Group shape=\"button\" size=\"medium\" value={hasArrow ? 'true' : 'false'} onChange={this.setValue.bind(this, 'hasArrow')}>\n <Radio value=\"true\">hasArrow=true</Radio>\n <Radio value=\"false\">hasArrow=false</Radio>\n </Radio.Group> : null}\n {iconOnly ?\n <Radio.Group shape=\"button\" size=\"medium\" value={hasTooltip ? 'true' : 'false'} onChange={this.setValue.bind(this, 'hasTooltip')}>\n <Radio value=\"true\">hasTooltip=true</Radio>\n <Radio value=\"false\">hasTooltip=false</Radio>\n </Radio.Group> : null}\n </div>\n <Nav style={{ width: '200px' }} iconOnly={iconOnly} hasArrow={hasArrow} hasTooltip={hasTooltip}>\n <Item icon=\"account\">Navigation One</Item>\n <Item icon=\"account\">Navigation Two</Item>\n <Item icon=\"account\">Navigation Three</Item>\n <Item icon=\"account\">Navigation Four</Item>\n <Item icon=\"account\">Navigation Five</Item>\n <SubNav icon=\"account\" label=\"Sub Nav\">\n <Item icon=\"account\">Item 1</Item>\n <Item icon=\"account\">Item 2</Item>\n <Item icon=\"account\">Item 3</Item>\n <Item icon=\"account\">Item 4</Item>\n </SubNav>\n </Nav>\n </div>\n );\n }\n}\n\nReactDOM.render(<App />, mountNode);
.demo-ctl {\n background-color: #F1F1F1;\n border-left: 4px solid #0D599A;\n color: #0A7AC3;\n margin-bottom: 20px;\n padding: 5px;\n}\n.demo-ctl .next-radio-group {\n margin: 5px;\n}
Nav 可设置 iconOnly 属性,只显示图标,以减少占用空间。
\n","order":"2"},"codes":{"jsx":"import { Nav, Radio } from '@alifd/next';\n\n\nconst { Item, SubNav } = Nav;\n\nclass App extends React.Component {\n state = {\n iconOnly: false,\n hasTooltip: true,\n hasArrow: true\n }\n\n setValue(name, value) {\n this.setState({\n [name]: value === 'true'\n });\n }\n\n render() {\n const { iconOnly, hasTooltip, hasArrow } = this.state;\n\n return (\nimport { Nav, Radio } from '@alifd/next';\n\n\nconst { Item, SubNav } = Nav;\n\nclass App extends React.Component {\n state = {\n iconOnly: false,\n hasTooltip: true,\n hasArrow: true\n }\n\n setValue(name, value) {\n this.setState({\n [name]: value === 'true'\n });\n }\n\n render() {\n const { iconOnly, hasTooltip, hasArrow } = this.state;\n\n return (\n <div>\n <div className=\"demo-ctl\">\n <Radio.Group shape=\"button\" size=\"medium\" value={iconOnly ? 'true' : 'false'} onChange={this.setValue.bind(this, 'iconOnly')}>\n <Radio value=\"true\">iconOnly=true</Radio>\n <Radio value=\"false\">iconOnly=false</Radio>\n </Radio.Group>\n {iconOnly ?\n <Radio.Group shape=\"button\" size=\"medium\" value={hasArrow ? 'true' : 'false'} onChange={this.setValue.bind(this, 'hasArrow')}>\n <Radio value=\"true\">hasArrow=true</Radio>\n <Radio value=\"false\">hasArrow=false</Radio>\n </Radio.Group> : null}\n {iconOnly ?\n <Radio.Group shape=\"button\" size=\"medium\" value={hasTooltip ? 'true' : 'false'} onChange={this.setValue.bind(this, 'hasTooltip')}>\n <Radio value=\"true\">hasTooltip=true</Radio>\n <Radio value=\"false\">hasTooltip=false</Radio>\n </Radio.Group> : null}\n </div>\n <Nav style={{ width: '200px' }} iconOnly={iconOnly} hasArrow={hasArrow} hasTooltip={hasTooltip}>\n <Item icon=\"account\">Navigation One</Item>\n <Item icon=\"account\">Navigation Two</Item>\n <Item icon=\"account\">Navigation Three</Item>\n <Item icon=\"account\">Navigation Four</Item>\n <Item icon=\"account\">Navigation Five</Item>\n <SubNav icon=\"account\" label=\"Sub Nav\">\n <Item icon=\"account\">Item 1</Item>\n <Item icon=\"account\">Item 2</Item>\n <Item icon=\"account\">Item 3</Item>\n <Item icon=\"account\">Item 4</Item>\n </SubNav>\n </Nav>\n </div>\n );\n }\n}\n\nReactDOM.render(<App />, mountNode);
.demo-ctl {\n background-color: #F1F1F1;\n border-left: 4px solid #0D599A;\n color: #0A7AC3;\n margin-bottom: 20px;\n padding: 5px;\n}\n.demo-ctl .next-radio-group {\n margin: 5px;\n}
When yout set mode of Nav to inline, openMode could controls the number of expanded sub navigation at same time.
\n","order":"4"},"codes":{"jsx":"import { Nav, Radio } from '@alifd/next';\n\nconst { Item, SubNav } = Nav;\n\nclass App extends React.Component {\n state = {\n openMode: 'single'\n }\n\n setValue(openMode) {\n this.setState({\n openMode\n });\n }\n\n render() {\n const { openMode } = this.state;\n\n return (\nimport { Nav, Radio } from '@alifd/next';\n\nconst { Item, SubNav } = Nav;\n\nclass App extends React.Component {\n state = {\n openMode: 'single'\n }\n\n setValue(openMode) {\n this.setState({\n openMode\n });\n }\n\n render() {\n const { openMode } = this.state;\n\n return (\n <div>\n <div className=\"demo-ctl\">\n <Radio.Group shape=\"button\" size=\"medium\" value={openMode} onChange={this.setValue.bind(this)}>\n <Radio value=\"single\">openMode=\"single\"</Radio>\n <Radio value=\"multiple\">openMode=\"multiple\"</Radio>\n </Radio.Group>\n </div>\n <Nav style={{ width: 240 }} openMode={openMode}>\n <SubNav label=\"Sub Nav 1\">\n <Item>Item 1</Item>\n </SubNav>\n <SubNav label=\"Sub Nav 2\">\n <Item>Item 1</Item>\n <Item>Item 2</Item>\n <SubNav label=\"Sub Nav 1\">\n <Item>Item 1</Item>\n <Item>Item 2</Item>\n </SubNav>\n <SubNav label=\"Sub Nav 2\">\n <Item>Item 1</Item>\n <Item>Item 2</Item>\n </SubNav>\n </SubNav>\n <SubNav label=\"Sub Nav 3\">\n <Item>Item 1</Item>\n <Item>Item 2</Item>\n <Item>Item 3</Item>\n <SubNav label=\"Sub Nav 1\">\n <Item>Item 1</Item>\n <Item>Item 2</Item>\n <Item>Item 3</Item>\n </SubNav>\n <SubNav label=\"Sub Nav 2\">\n <Item>Item 1</Item>\n <Item>Item 2</Item>\n <Item>Item 3</Item>\n </SubNav>\n <SubNav label=\"Sub Nav 3\">\n <Item>Item 1</Item>\n <Item>Item 2</Item>\n <Item>Item 3</Item>\n </SubNav>\n </SubNav>\n <Item>Item</Item>\n </Nav>\n </div>);\n }\n}\n\nReactDOM.render(<App />, mountNode);
.demo-ctl {\n background-color: #F1F1F1;\n border-left: 4px solid #0D599A;\n color: #0A7AC3;\n margin-bottom: 20px;\n padding: 5px;\n}\n.demo-ctl .next-radio-group {\n margin: 5px;\n}
当 Nav 的 mode="inline" 时,openMode 可控制同级内联子导航的展开数量。
\n","order":"4"},"codes":{"jsx":"import { Nav, Radio } from '@alifd/next';\n\nconst { Item, SubNav } = Nav;\n\nclass App extends React.Component {\n state = {\n openMode: 'single'\n }\n\n setValue(openMode) {\n this.setState({\n openMode\n });\n }\n\n render() {\n const { openMode } = this.state;\n\n return (\nimport { Nav, Radio } from '@alifd/next';\n\nconst { Item, SubNav } = Nav;\n\nclass App extends React.Component {\n state = {\n openMode: 'single'\n }\n\n setValue(openMode) {\n this.setState({\n openMode\n });\n }\n\n render() {\n const { openMode } = this.state;\n\n return (\n <div>\n <div className=\"demo-ctl\">\n <Radio.Group shape=\"button\" size=\"medium\" value={openMode} onChange={this.setValue.bind(this)}>\n <Radio value=\"single\">openMode=\"single\"</Radio>\n <Radio value=\"multiple\">openMode=\"multiple\"</Radio>\n </Radio.Group>\n </div>\n <Nav style={{ width: 240 }} openMode={openMode}>\n <SubNav label=\"Sub Nav 1\">\n <Item>Item 1</Item>\n </SubNav>\n <SubNav label=\"Sub Nav 2\">\n <Item>Item 1</Item>\n <Item>Item 2</Item>\n <SubNav label=\"Sub Nav 1\">\n <Item>Item 1</Item>\n <Item>Item 2</Item>\n </SubNav>\n <SubNav label=\"Sub Nav 2\">\n <Item>Item 1</Item>\n <Item>Item 2</Item>\n </SubNav>\n </SubNav>\n <SubNav label=\"Sub Nav 3\">\n <Item>Item 1</Item>\n <Item>Item 2</Item>\n <Item>Item 3</Item>\n <SubNav label=\"Sub Nav 1\">\n <Item>Item 1</Item>\n <Item>Item 2</Item>\n <Item>Item 3</Item>\n </SubNav>\n <SubNav label=\"Sub Nav 2\">\n <Item>Item 1</Item>\n <Item>Item 2</Item>\n <Item>Item 3</Item>\n </SubNav>\n <SubNav label=\"Sub Nav 3\">\n <Item>Item 1</Item>\n <Item>Item 2</Item>\n <Item>Item 3</Item>\n </SubNav>\n </SubNav>\n <Item>Item</Item>\n </Nav>\n </div>);\n }\n}\n\nReactDOM.render(<App />, mountNode);
.demo-ctl {\n background-color: #F1F1F1;\n border-left: 4px solid #0D599A;\n color: #0A7AC3;\n margin-bottom: 20px;\n padding: 5px;\n}\n.demo-ctl .next-radio-group {\n margin: 5px;\n}
When you set mode of Nav to popup, popAlign could controls the alignment of the pop sub navigation.
\n","order":"5"},"codes":{"jsx":"import { Nav, Radio } from '@alifd/next';\n\nconst { Item, SubNav } = Nav;\n\nclass App extends React.Component {\n state = {\n popupAlign: 'follow'\n }\n\n setValue(popupAlign) {\n this.setState({\n popupAlign\n });\n }\n\n render() {\n const { popupAlign } = this.state;\n\n return (\nimport { Nav, Radio } from '@alifd/next';\n\nconst { Item, SubNav } = Nav;\n\nclass App extends React.Component {\n state = {\n popupAlign: 'follow'\n }\n\n setValue(popupAlign) {\n this.setState({\n popupAlign\n });\n }\n\n render() {\n const { popupAlign } = this.state;\n\n return (\n <div>\n <div className=\"demo-ctl\">\n <Radio.Group shape=\"button\" size=\"medium\" value={popupAlign} onChange={this.setValue.bind(this)}>\n <Radio value=\"follow\">popupAlign=\"follow\"</Radio>\n <Radio value=\"outside\">popupAlign=\"outside\"</Radio>\n </Radio.Group>\n </div>\n <Nav style={{ height: 400, width: 240 }} mode=\"popup\" popupAlign={popupAlign} defaultOpenKeys={['sub-nav-2']}>\n <SubNav key=\"sub-nav-1\"label=\"Sub Nav 1\">\n <Item key=\"1\">Item 1</Item>\n </SubNav>\n <SubNav key=\"sub-nav-2\" label=\"Sub Nav 2\">\n <Item key=\"1\">Item 1</Item>\n <Item key=\"2\">Item 2</Item>\n </SubNav>\n <SubNav key=\"sub-nav-3\" label=\"Sub Nav 3\">\n <Item key=\"1\">Item 1</Item>\n <Item key=\"2\">Item 2</Item>\n <Item key=\"3\">Item 3</Item>\n </SubNav>\n <SubNav key=\"sub-nav-4\" label=\"Sub Nav 4\">\n <Item key=\"1\">Item 1</Item>\n <Item key=\"2\">Item 2</Item>\n <Item key=\"3\">Item 3</Item>\n <Item key=\"4\">Item 4</Item>\n </SubNav>\n </Nav>\n </div>\n );\n }\n}\n\nReactDOM.render(<App />, mountNode);
.demo-ctl {\n background-color: #F1F1F1;\n border-left: 4px solid #0D599A;\n color: #0A7AC3;\n margin-bottom: 20px;\n padding: 5px;\n}\n.demo-ctl .next-radio-group {\n margin: 5px;\n}
当 Nav 的 mode="popup" 时,popAlign 可控制弹出子导航的对齐方式。
\n","order":"5"},"codes":{"jsx":"import { Nav, Radio } from '@alifd/next';\n\nconst { Item, SubNav } = Nav;\n\nclass App extends React.Component {\n state = {\n popupAlign: 'follow'\n }\n\n setValue(popupAlign) {\n this.setState({\n popupAlign\n });\n }\n\n render() {\n const { popupAlign } = this.state;\n\n return (\nimport { Nav, Radio } from '@alifd/next';\n\nconst { Item, SubNav } = Nav;\n\nclass App extends React.Component {\n state = {\n popupAlign: 'follow'\n }\n\n setValue(popupAlign) {\n this.setState({\n popupAlign\n });\n }\n\n render() {\n const { popupAlign } = this.state;\n\n return (\n <div>\n <div className=\"demo-ctl\">\n <Radio.Group shape=\"button\" size=\"medium\" value={popupAlign} onChange={this.setValue.bind(this)}>\n <Radio value=\"follow\">popupAlign=\"follow\"</Radio>\n <Radio value=\"outside\">popupAlign=\"outside\"</Radio>\n </Radio.Group>\n </div>\n <Nav style={{ height: 400, width: 240 }} mode=\"popup\" popupAlign={popupAlign} defaultOpenKeys={['sub-nav-2']}>\n <SubNav key=\"sub-nav-1\"label=\"Sub Nav 1\">\n <Item key=\"1\">Item 1</Item>\n </SubNav>\n <SubNav key=\"sub-nav-2\" label=\"Sub Nav 2\">\n <Item key=\"1\">Item 1</Item>\n <Item key=\"2\">Item 2</Item>\n </SubNav>\n <SubNav key=\"sub-nav-3\" label=\"Sub Nav 3\">\n <Item key=\"1\">Item 1</Item>\n <Item key=\"2\">Item 2</Item>\n <Item key=\"3\">Item 3</Item>\n </SubNav>\n <SubNav key=\"sub-nav-4\" label=\"Sub Nav 4\">\n <Item key=\"1\">Item 1</Item>\n <Item key=\"2\">Item 2</Item>\n <Item key=\"3\">Item 3</Item>\n <Item key=\"4\">Item 4</Item>\n </SubNav>\n </Nav>\n </div>\n );\n }\n}\n\nReactDOM.render(<App />, mountNode);
.demo-ctl {\n background-color: #F1F1F1;\n border-left: 4px solid #0D599A;\n color: #0A7AC3;\n margin-bottom: 20px;\n padding: 5px;\n}\n.demo-ctl .next-radio-group {\n margin: 5px;\n}
It provides top navigation and side navigation, the top navigation provides global categories and functions, and the side navigation provides a multi-level structure to store and arrange the site architecture.
\niconOnly only works with the vertical direction.
\nThe property of Nav inherits from Menu, so in addition to special instructions, you can use the API of Menu.
\n\n\nThe API inherits from
\nMenu
, please look at theMenu
document
Param | \nDescripiton | \nType | \nDefault Value | \n
---|---|---|---|
children | \nnavigation item and sub navigation | \nReactNode | \n- | \n
type | \ntype of navigation option: 'normal' 'primary' 'secondary' 'line' | \nEnum | \n'normal' | \n
direction | \nlayout of navigation option: 'hoz' 'ver' | \nEnum | \n'ver' | \n
hozAlign | \nalignment of items in the horizontal nav bar, only works when direction is set to 'hoz' and the header exists options: 'left', 'right' | \nEnum | \n'left' | \n
activeDirection | \nthe active border direction of the selected item option: null 'top' 'bottom' 'left' 'right' | \nEnum | \nwhen direction is 'hoz', the default value is 'bottom'. When direction is 'ver', the default value is 'left'. | \n
mode | \nsub navigation open mode (horizontal navigation only supports pop up) option: 'inline', 'popup' | \nEnum | \n'inline' | \n
triggerType | \nsub navigation open trigger option: 'click', 'hover' | \nEnum | \n'click' | \n
inlineIndent | \ninline sub navigation indent distance | \nNumber | \n20 | \n
defaultOpenAll | \nopen all subnavs default, only when mode is set to 'inline' and openMode is set to 'multiple' | \nBoolean | \nfalse | \n
openMode | \nthe open mode of inline sub navigation, expand a peer navigation or multiple navigations at the same level at same time, it only works in inline mode option: 'single', 'multiple' | \nEnum | \n'multiple' | \n
selectedKeys | \nkeys of selected nav item currently | \nString/Array | \n- | \n
defaultSelectedKeys | \nkeys of selected nav item in default | \nString/Array | \n[] | \n
onSelect | \ncallback function triggered when select or unselect nav item signatures: Function(selectedKeys: Array, item: Object, extra: Object) => void params: selectedKeys: {Array} keys of selected nav item item: {Object} current operation nav item extra: {Object} extra params extra.select: {Boolean} whether is selected extra.key: {Array} key of current operation nav item extra.label: {Object} label of current operation nav item extra.keyPath: {Array} key path of current operation nav item | \nFunction | \n() => {} | \n
popupAlign | \npop up sub navigation alignment (horizontal navigation only supports follow) option: 'follow', 'outside' | \nEnum | \n'follow' | \n
popupClassName | \npop up navigation custom class name | \nString | \n- | \n
iconOnly | \nwhether to show only icons | \nBoolean | \n- | \n
hasArrow | \nwhether to display the right arrow (only works when iconOnly=true) | \nBoolean | \ntrue | \n
hasTooltip | \nwhether has tool tip (only works when iconOnly=true) | \nBoolean | \nfalse | \n
header | \ncustom navigation head | \nReactNode | \n- | \n
footer | \ncustom navigation footer | \nReactNode | \n- | \n
embeddable | \nintegrate with the background or not(which means no background/border/box-shadow etc.), usually used with Layout. You can also custom its height like<Nav style={{lineHeight: '100px'}}> | \nBoolean | \nfalse | \n
\n\nThe API inherits from
\nMenu.Group
, please look at theMenu.Group
document
Param | \nDescripiton | \nType | \nDefault Value | \n
---|---|---|---|
label | \ncontent of label | \nReactNode | \n- | \n
children | \nnavigation item and sub navigation | \nReactNode | \n- | \n
\n\nThe API inherits from
\nMenu.Item
, please look at theMenu.Item
document
Param | \nDescripiton | \nType | \nDefault Value | \n
---|---|---|---|
icon | \ncustom icon, it can be type of Icon or such as <Icon type="icon type" /> | \nString/ReactNode | \n- | \n
children | \ncontent of navigation item | \nReactNode | \n- | \n
\n\nThe API inherits from
\nMenu.PopupItem
, please look at theMenu.PopupItem
document
Param | \nDescripiton | \nType | \nDefault Value | \n
---|---|---|---|
icon | \ncustom icon, it can be type of Icon or such as <Icon type="icon type" /> | \nString/ReactNode | \n- | \n
label | \ncontent of label | \nReactNode | \n- | \n
children | \npopup content | \nReactNode | \n- | \n
\n\nThe API inherits from
\nMenu.SubMenu
, please look at theMenu.SubMenu
document
Param | \nDescripiton | \nType | \nDefault Value | \n
---|---|---|---|
icon | \ncustom icon, it can be type of Icon or such as <Icon type="icon type" /> | \nString/ReactNode | \n- | \n
label | \ncontent of label | \nReactNode | \n- | \n
selectable | \nwhether is selectable | \nBoolean | \nfalse | \n
children | \nnavigation item and sub navigation | \nReactNode | \n- | \n
KeyBoard | \nDescripiton | \n
---|---|
Up Arrow | \nnavigate to previous item | \n
Down Arrow | \nnavigate to next item | \n
Right Arrow | \nopen the submenu, navigate to the first item of the submenu; horizontal menu bar first level, navigate to the right one | \n
Left Arrow | \nclose the submenu, navigate to the parent menu; horizontal menu bar first level, navigation to the left one | \n
Enter | \nopen submenu and navigate to the first item of the submenu | \n
Esc | \nclose submenu and navigate to the parent menu item | \n
分为顶部导航和侧边导航,顶部导航提供全局性的类目和功能,侧边导航提供多级结构来收纳和排列网站架构。
\niconOnly 只适用垂直方向。
\nNav 继承自 Menu,除特殊说明外,可使用 Menu 的 API。
\n\n\n继承自
\nMenu
的能力请查看Menu
文档
参数 | \n说明 | \n类型 | \n默认值 | \n
---|---|---|---|
children | \n导航项和子导航 | \nReactNode | \n- | \n
type | \n导航类型 可选值: 'normal'(普通) 'primary'(主要) 'secondary'(次要) 'line'(线形) | \nEnum | \n'normal' | \n
direction | \n导航布局 可选值: 'hoz'(水平) 'ver'(垂直) | \nEnum | \n'ver' | \n
hozAlign | \n横向导航条 items 和 footer 的对齐方向,在 direction 设置为 'hoz' 并且 header 存在时生效 可选值: 'left', 'right' | \nEnum | \n'left' | \n
activeDirection | \n设置组件选中状态的 active 边方向 可选值: null(无) 'top'(上) 'bottom'(下) 'left'(左) 'right'(右) | \nEnum | \n当 direction 为 'hoz' 时,默认值为 'bottom',当 direction 为 'ver' 时,默认值为 'left' | \n
mode | \n子导航打开的模式(水平导航只支持弹出) 可选值: 'inline', 'popup' | \nEnum | \n'inline' | \n
triggerType | \n子导航打开的触发方式 可选值: 'click', 'hover' | \nEnum | \n'click' | \n
inlineIndent | \n内联子导航缩进距离 | \nNumber | \n20 | \n
defaultOpenAll | \n初始展开所有的子导航,只在 mode 设置为 'inline' 以及 openMode 设置为 'multiple' 下生效 | \nBoolean | \nfalse | \n
openMode | \n内联子导航的展开模式,同时可以展开一个同级子导航还是多个同级子导航,该属性仅在 mode 为 inline 时生效 可选值: 'single', 'multiple' | \nEnum | \n'multiple' | \n
selectedKeys | \n当前选中导航项的 key 值 | \nString/Array | \n- | \n
defaultSelectedKeys | \n初始选中导航项的 key 值 | \nString/Array | \n[] | \n
onSelect | \n选中或取消选中导航项触发的回调函数 签名: Function(selectedKeys: Array, item: Object, extra: Object) => void 参数: selectedKeys: {Array} 选中的所有导航项的 key item: {Object} 选中或取消选中的导航项 extra: {Object} 额外参数 extra.select: {Boolean} 是否是选中 extra.key: {Array} 导航项的 key extra.label: {Object} 导航项的文本 extra.keyPath: {Array} 导航项 key 的路径 | \nFunction | \n- | \n
popupAlign | \n弹出子导航的对齐方式(水平导航只支持 follow ) 可选值: 'follow', 'outside' | \nEnum | \n'follow' | \n
popupClassName | \n弹出子导航的自定义类名 | \nString | \n- | \n
iconOnly | \n是否只显示图标 | \nBoolean | \n- | \n
hasArrow | \n是否显示右侧的箭头(仅在 iconOnly=true 时生效) | \nBoolean | \ntrue | \n
hasTooltip | \n是否有 ToolTips (仅在 iconOnly=true 时生效) | \nBoolean | \nfalse | \n
header | \n自定义导航头部 | \nReactNode | \n- | \n
footer | \n自定义导航尾部 | \nReactNode | \n- | \n
embeddable | \n是否开启嵌入式模式,一般用于Layout的布局中,开启后没有默认背景、外层border、box-shadow,可以配合<Nav style={{lineHeight: '100px'}}> 自定义高度 | \nBoolean | \nfalse | \n
\n\n继承自
\nMenu.Group
的能力请查看Menu.Group
文档
参数 | \n说明 | \n类型 | \n默认值 | \n
---|---|---|---|
label | \n标签内容 | \nReactNode | \n- | \n
children | \n导航项和子导航 | \nReactNode | \n- | \n
\n\n继承自
\nMenu.Item
的能力请查看Menu.Item
文档
参数 | \n说明 | \n类型 | \n默认值 | \n
---|---|---|---|
icon | \n自定义图标,可以使用 Icon 的 type,也可以使用组件 <Icon type="icon type" /> | \nString/ReactNode | \n- | \n
children | \n导航内容 | \nReactNode | \n- | \n
\n\n继承自
\nMenu.PopupItem
的能力请查看Menu.PopupItem
文档
参数 | \n说明 | \n类型 | \n默认值 | \n
---|---|---|---|
icon | \n自定义图标,可以使用 Icon 的 type, 也可以使用组件 <Icon type="icon type" /> | \nString/ReactNode | \n- | \n
label | \n标签内容 | \nReactNode | \n- | \n
children | \n弹出内容 | \nReactNode | \n- | \n
\n\n继承自
\nMenu.SubMenu
的能力请查看Menu.SubMenu
文档
参数 | \n说明 | \n类型 | \n默认值 | \n
---|---|---|---|
icon | \n自定义图标,可以使用 Icon 的 type,也可以使用组件 <Icon type="your type" /> | \nString/ReactNode | \n- | \n
label | \n标签内容 | \nReactNode | \n- | \n
selectable | \n是否可选 | \nBoolean | \nfalse | \n
children | \n导航项和子导航 | \nReactNode | \n- | \n
按键 | \n说明 | \n
---|---|
Up Arrow | \n导航到上一项 | \n
Down Arrow | \n导航到下一项 | \n
Right Arrow | \n打开子菜单,导航到子菜单第一项;横向菜单条第一层,导航到右一项 | \n
Left Arrow | \n关闭子菜单,导航到父级菜单;横向菜单条第一层,导航到左一项 | \n
Enter | \n打开子菜单,导航到子菜单第一项 | \n
Esc | \n关闭子菜单,导航到父级菜单 | \n
Simplest use, closed after 4.5
\n","order":"0"},"codes":{"jsx":"import { Notification, Button } from '@alifd/next';\n\nconst openNotification = () => {\n Notification.open({\n title: 'Notification Title',\n content: 'This is the content of the notification. This is the content of the notification. This is the content of the notification.',\n onClick: () => {\n console.log('Notification Clicked!');\n },\n });\n};\n\nReactDOM.render(\n ,\n mountNode,\n);\n"},"body":"\n```jsx\nimport { Notification, Button } from '@alifd/next';\n\nconst openNotification = () => {\n Notification.open({\n title: 'Notification Title',\n content: 'This is the content of the notification. This is the content of the notification. This is the content of the notification.',\n onClick: () => {\n console.log('Notification Clicked!');\n },\n });\n};\n\nReactDOM.render(\n ,\n mountNode,\n);\n```","html":"import { Notification, Button } from '@alifd/next';\n\nconst openNotification = () => {\n Notification.open({\n title: 'Notification Title',\n content: 'This is the content of the notification. This is the content of the notification. This is the content of the notification.',\n onClick: () => {\n console.log('Notification Clicked!');\n },\n });\n};\n\nReactDOM.render(\n <Button type=\"primary\" onClick={openNotification}>\n Open Notification\n </Button>,\n mountNode,\n);
最简单的用法, 4.5s 后关闭
\n","order":"0"},"codes":{"jsx":"import { Notification, Button } from '@alifd/next';\n\nconst openNotification = () => {\n Notification.open({\n title: 'Notification Title',\n content: 'This is the content of the notification. This is the content of the notification. This is the content of the notification.',\n onClick: () => {\n console.log('Notification Clicked!');\n },\n });\n};\n\nReactDOM.render(\n ,\n mountNode,\n);\n"},"body":"\n\n```jsx\nimport { Notification, Button } from '@alifd/next';\n\nconst openNotification = () => {\n Notification.open({\n title: 'Notification Title',\n content: 'This is the content of the notification. This is the content of the notification. This is the content of the notification.',\n onClick: () => {\n console.log('Notification Clicked!');\n },\n });\n};\n\nReactDOM.render(\n ,\n mountNode,\n);\n```","html":"import { Notification, Button } from '@alifd/next';\n\nconst openNotification = () => {\n Notification.open({\n title: 'Notification Title',\n content: 'This is the content of the notification. This is the content of the notification. This is the content of the notification.',\n onClick: () => {\n console.log('Notification Clicked!');\n },\n });\n};\n\nReactDOM.render(\n <Button type=\"primary\" onClick={openNotification}>\n Open Notification\n </Button>,\n mountNode,\n);
Duration
can be used to specify how long the notification stays open. After the duration time elapses, the notification closes automatically. If not specified, default value is 4.5 seconds. If you set the value to 0, the notification box will never close automatically.
import { Notification, Button, NumberPicker } from '@alifd/next';\n\nlet duration = 4500;\nconst openNotification = () => {\n const args = {\n title: 'Notification Title',\n content: 'I will never close automatically. I will be close automatically. I will never close automatically.',\n duration,\n };\n Notification.open(args);\n};\n\nReactDOM.render(\n <div>\n <NumberPicker defaultValue={duration} onChange={(v) => (duration = v || 0)} />\n <Button type=\"primary\" onClick={openNotification} style={{marginLeft: 20}}>\n Open Notification\n </Button>\n </div>,\n mountNode,\n);
自定义关闭的延迟,默认 4.5s
, 为 0
时则一直存在
import { Notification, Button, NumberPicker } from '@alifd/next';\n\nlet duration = 4500;\nconst openNotification = () => {\n const args = {\n title: 'Notification Title',\n content: 'I will never close automatically. I will be close automatically. I will never close automatically.',\n duration,\n };\n Notification.open(args);\n};\n\nReactDOM.render(\n <div>\n <NumberPicker defaultValue={duration} onChange={(v) => (duration = v || 0)} />\n <Button type=\"primary\" onClick={openNotification} style={{marginLeft: 20}}>\n Open Notification\n </Button>\n </div>,\n mountNode,\n);
Change Icon
\n","order":"1"},"codes":{"jsx":"import { Notification, Button } from '@alifd/next';\n\nconst openNotification = () => {\n const args = {\n title: 'Notification Title',\n content: 'I will never close automatically. I will be close automatically. I will never close automatically.',\n icon: 'smile'\n };\n Notification.open(args);\n};\n\nReactDOM.render(\nimport { Notification, Button } from '@alifd/next';\n\nconst openNotification = () => {\n const args = {\n title: 'Notification Title',\n content: 'I will never close automatically. I will be close automatically. I will never close automatically.',\n icon: 'smile'\n };\n Notification.open(args);\n};\n\nReactDOM.render(\n <div>\n <Button type=\"primary\" onClick={openNotification} style={{marginLeft: 20}}>\n Open Notification\n </Button>\n </div>,\n mountNode,\n);
可以设置使用的图标
\n","order":"2"},"codes":{"jsx":"import { Notification, Button } from '@alifd/next';\n\nconst openNotification = () => {\n const args = {\n title: 'Notification Title',\n content: 'I will never close automatically. I will be close automatically. I will never close automatically.',\n icon: 'smile'\n };\n Notification.open(args);\n};\n\nReactDOM.render(\nimport { Notification, Button } from '@alifd/next';\n\nconst openNotification = () => {\n const args = {\n title: 'Notification Title',\n content: 'I will never close automatically. I will be close automatically. I will never close automatically.',\n icon: 'smile'\n };\n Notification.open(args);\n};\n\nReactDOM.render(\n <div>\n <Button type=\"primary\" onClick={openNotification} style={{marginLeft: 20}}>\n Open Notification\n </Button>\n </div>,\n mountNode,\n);
More level Noticfiction
\n","order":"3"},"codes":{"jsx":"import { Notification, Button } from '@alifd/next';\n\nconst openNotification = (type) => {\n Notification.open({\n title: 'Notification Title',\n content: 'This is the content of the notification. This is the content of the notification. This is the content of the notification.',\n type,\n });\n};\n\nReactDOM.render(\nimport { Notification, Button } from '@alifd/next';\n\nconst openNotification = (type) => {\n Notification.open({\n title: 'Notification Title',\n content: 'This is the content of the notification. This is the content of the notification. This is the content of the notification.',\n type,\n });\n};\n\nReactDOM.render(\n <div className=\"button-row\">\n <Button onClick={() => openNotification('success')}>\n success\n </Button>\n <Button onClick={() => openNotification('warning')}>\n warning\n </Button>\n <Button onClick={() => openNotification('error')}>\n error\n </Button>\n <Button onClick={() => openNotification('notice')}>\n notice\n </Button>\n <Button onClick={() => openNotification('help')}>\n help\n </Button>\n </div>,\n mountNode,\n);
.button-row .next-btn {\n margin-right: 10px;\n}
success
, warning
, error
, notice
, help
类型的通知框
import { Notification, Button } from '@alifd/next';\n\nconst openNotification = (type) => {\n Notification.open({\n title: 'Notification Title',\n content: 'This is the content of the notification. This is the content of the notification. This is the content of the notification.',\n type,\n });\n};\n\nReactDOM.render(\n <div className=\"button-row\">\n <Button onClick={() => openNotification('success')}>\n success\n </Button>\n <Button onClick={() => openNotification('warning')}>\n warning\n </Button>\n <Button onClick={() => openNotification('error')}>\n error\n </Button>\n <Button onClick={() => openNotification('notice')}>\n notice\n </Button>\n <Button onClick={() => openNotification('help')}>\n help\n </Button>\n </div>,\n mountNode,\n);
.button-row .next-btn {\n margin-right: 10px;\n}
Can setting tl
, tr
, bl
, br
import { Notification, Button } from '@alifd/next';\n\nconst openNotification = (placement) => {\n Notification.config({placement});\n Notification.open({\n title: 'Notification Title',\n content:\n 'This is the content of the notification. This is the content of the notification. This is the content of the notification.',\n });\n};\n\nReactDOM.render(\n <div className=\"button-row\">\n <Button onClick={() => openNotification('tl')}>\n Top Left\n </Button>\n <Button onClick={() => openNotification('tr')}>\n Top Right\n </Button>\n <Button onClick={() => openNotification('bl')}>\n Bottom Left\n </Button>\n <Button onClick={() => openNotification('br')}>\n Bottom Right\n </Button>\n </div>,\n mountNode,\n);
.button-row .next-btn {\n margin-right: 10px;\n}
可以设置通知从右上角、右下角、左下角、左上角弹出。
\n","order":"4"},"codes":{"jsx":"import { Notification, Button } from '@alifd/next';\n\nconst openNotification = (placement) => {\n Notification.config({placement});\n Notification.open({\n title: 'Notification Title',\n content:\n 'This is the content of the notification. This is the content of the notification. This is the content of the notification.',\n });\n};\n\nReactDOM.render(\nimport { Notification, Button } from '@alifd/next';\n\nconst openNotification = (placement) => {\n Notification.config({placement});\n Notification.open({\n title: 'Notification Title',\n content:\n 'This is the content of the notification. This is the content of the notification. This is the content of the notification.',\n });\n};\n\nReactDOM.render(\n <div className=\"button-row\">\n <Button onClick={() => openNotification('tl')}>\n Top Left\n </Button>\n <Button onClick={() => openNotification('tr')}>\n Top Right\n </Button>\n <Button onClick={() => openNotification('bl')}>\n Bottom Left\n </Button>\n <Button onClick={() => openNotification('br')}>\n Bottom Right\n </Button>\n </div>,\n mountNode,\n);
.button-row .next-btn {\n margin-right: 10px;\n}
use style
or className
to custom style;
import { Notification, Button } from '@alifd/next';\n\nconst openNotification = () => {\n Notification.open({\n title: 'Notification Title',\n content:\n 'This is the content of the notification. This is the content of the notification. This is the content of the notification.',\n style: {\n width: 600,\n marginLeft: -225,\n },\n });\n};\n\nReactDOM.render(\n <Button type=\"primary\" onClick={openNotification}>\n Open Notification\n </Button>,\n mountNode,\n);
使用 style 和 className 来定义样式。
\n","order":"5"},"codes":{"jsx":"import { Notification, Button } from '@alifd/next';\n\nconst openNotification = () => {\n Notification.open({\n title: 'Notification Title',\n content:\n 'This is the content of the notification. This is the content of the notification. This is the content of the notification.',\n style: {\n width: 600,\n marginLeft: -225,\n },\n });\n};\n\nReactDOM.render(\n ,\n mountNode,\n);\n"},"body":"\n\n```jsx\nimport { Notification, Button } from '@alifd/next';\n\nconst openNotification = () => {\n Notification.open({\n title: 'Notification Title',\n content:\n 'This is the content of the notification. This is the content of the notification. This is the content of the notification.',\n style: {\n width: 600,\n marginLeft: -225,\n },\n });\n};\n\nReactDOM.render(\n ,\n mountNode,\n);\n```","html":"import { Notification, Button } from '@alifd/next';\n\nconst openNotification = () => {\n Notification.open({\n title: 'Notification Title',\n content:\n 'This is the content of the notification. This is the content of the notification. This is the content of the notification.',\n style: {\n width: 600,\n marginLeft: -225,\n },\n });\n};\n\nReactDOM.render(\n <Button type=\"primary\" onClick={openNotification}>\n Open Notification\n </Button>,\n mountNode,\n);
Update content with unique key.
\n","order":"6"},"codes":{"jsx":"import { Notification, Button } from '@alifd/next';\n\nconst key = 'updatable';\n\nconst openNotification = () => {\n Notification.open({\n key,\n title: 'Notification Title',\n content: 'description.',\n });\n setTimeout(() => {\n Notification.open({\n key,\n title: 'New Title',\n content: 'New description.',\n });\n }, 1000);\n};\n\nReactDOM.render(\n ,\n mountNode,\n);\n"},"body":"\n```jsx\nimport { Notification, Button } from '@alifd/next';\n\nconst key = 'updatable';\n\nconst openNotification = () => {\n Notification.open({\n key,\n title: 'Notification Title',\n content: 'description.',\n });\n setTimeout(() => {\n Notification.open({\n key,\n title: 'New Title',\n content: 'New description.',\n });\n }, 1000);\n};\n\nReactDOM.render(\n ,\n mountNode,\n);\n```","html":"import { Notification, Button } from '@alifd/next';\n\nconst key = 'updatable';\n\nconst openNotification = () => {\n Notification.open({\n key,\n title: 'Notification Title',\n content: 'description.',\n });\n setTimeout(() => {\n Notification.open({\n key,\n title: 'New Title',\n content: 'New description.',\n });\n }, 1000);\n};\n\nReactDOM.render(\n <Button type=\"primary\" onClick={openNotification}>\n Open Notification\n </Button>,\n mountNode,\n);
可以通过唯一的 key 来更新内容。
\n","order":"6"},"codes":{"jsx":"import { Notification, Button } from '@alifd/next';\n\nconst key = 'updatable';\n\nconst openNotification = () => {\n Notification.open({\n key,\n title: 'Notification Title',\n content: 'description.',\n });\n setTimeout(() => {\n Notification.open({\n key,\n title: 'New Title',\n content: 'New description.',\n });\n }, 1000);\n};\n\nReactDOM.render(\n ,\n mountNode,\n);\n"},"body":"\n\n```jsx\nimport { Notification, Button } from '@alifd/next';\n\nconst key = 'updatable';\n\nconst openNotification = () => {\n Notification.open({\n key,\n title: 'Notification Title',\n content: 'description.',\n });\n setTimeout(() => {\n Notification.open({\n key,\n title: 'New Title',\n content: 'New description.',\n });\n }, 1000);\n};\n\nReactDOM.render(\n ,\n mountNode,\n);\n```","html":"import { Notification, Button } from '@alifd/next';\n\nconst key = 'updatable';\n\nconst openNotification = () => {\n Notification.open({\n key,\n title: 'Notification Title',\n content: 'description.',\n });\n setTimeout(() => {\n Notification.open({\n key,\n title: 'New Title',\n content: 'New description.',\n });\n }, 1000);\n};\n\nReactDOM.render(\n <Button type=\"primary\" onClick={openNotification}>\n Open Notification\n </Button>,\n mountNode,\n);
Display a notification message globally.
\nTo display a notification message at any of the four corners of the viewport. Typically it can be used in the following cases:
\nNotification.success(config)
Notification.error(config)
Notification.warning(config)
Notification.notice(config)
Notification.help(config)
Notification.open(config)
Notification.close(key: String)
Notification.destroy()
The properties of config are as follows:
\nProperty | \nDescription | \nType | \nDefault | \nVersion | \n|
---|---|---|---|---|---|
key | \nThe unique identifier of the Notification | \nString | \n- | \n\n | |
title | \nThe title of notification box (required) | \nString\\ | \nReactNode | \n- | \n\n |
content | \nThe content of notification box (required) | \nString\\ | \nReactNode | \n- | \n\n |
duration | \nTime in seconds before Notification is closed. When set to 0 or null, it will never be closed automatically | \nNumber | \n4.5 | \n\n | |
icon | \nCustomized icon | \nReactNode | \n- | \n\n | |
style | \nCustomized inline style | \nReact.CSSProperties | \n- | \n\n | |
className | \nCustomized CSS class | \nString | \n- | \n\n | |
onClose | \nSpecify a function that will be called when the close button is clicked | \nFunction | \n- | \n\n | |
onClick | \nSpecify a function that will be called when the notification is clicked | \nFunction | \n- | \n
notification
also provides a global config()
method that can be used for specifying the default options. Once this method is used, all the notification boxes will take into account these globally defined options when displaying.
Notification.config(options)
Notification.config({\n placement: 'bottomRight',\n duration: 3000,\n});
Property | \nDescription | \nType | \nDefault | \nVersion | \n
---|---|---|---|---|
duration | \nTime in seconds before Notification is closed. When set to 0 or null, it will never be closed automatically | \nNumber | \n4.5 | \n\n |
maxCount | \nMax visible count, default Infinity | \nNumber | \n- | \n\n |
getContainer | \nReturn the mount node for Notification | \n() => HTMLNode | \n() => document.body | \n\n |
offset | \nOffset after align, [x, y] | \nArray | \n[30, 30] | \n\n |
placement | \nPosition of Notification, can be one of tl tr bl br | \nString | \ntopRight | \n\n |
size | \nUse Message size prop | \nString | \nlarge | \n
全局展示通知提醒信息。
\n在系统四个角显示通知提醒信息。经常用于以下情况:
\nNotification.success(config)
Notification.error(config)
Notification.warning(config)
Notification.notice(config)
Notification.help(config)
Notification.open(config)
Notification.close(key: String)
Notification.destroy()
config 参数如下:
\n参数 | \n说明 | \n类型 | \n默认值 | \n版本 | \n|
---|---|---|---|---|---|
key | \n当前通知唯一标志, 默认会自动生成 | \nString | \n- | \n\n | |
title | \n通知提醒标题,必选 | \nString\\ | \nReactNode | \n- | \n\n |
content | \n通知提醒内容,必选 | \nString\\ | \nReactNode | \n- | \n\n |
duration | \n默认 4.5 秒后自动关闭,配置为 0 则不自动关闭 | \nNumber | \n4.5 | \n\n | |
icon | \n自定义图标 | \nReactNode | \n- | \n\n | |
style | \n自定义内联样式 | \nReact.CSSProperties | \n- | \n\n | |
className | \n自定义 CSS class | \nString | \n- | \n\n | |
onClose | \n点击默认关闭按钮时触发的回调函数 | \nFunction | \n- | \n\n | |
onClick | \n点击通知时触发的回调函数 | \nFunction | \n- | \n
还提供了一个全局配置方法,在调用前提前配置,全局一次生效。
\nNotification.config(options)
Notification.config({\n placement: 'bottomRight',\n duration: 3000,\n});
参数 | \n说明 | \n类型 | \n默认值 | \n版本 | \n
---|---|---|---|---|
duration | \n默认自动关闭延时,单位秒 | \nNumber | \n4.5 | \n\n |
maxCount | \n最多同时出现的个数, 默认不限制 | \nNumber | \n- | \n\n |
getContainer | \n配置渲染节点的输出位置 | \n() => HTMLNode | \n() => document.body | \n\n |
offset | \n\b对齐之后的偏移 [x, y] | \nArray | \n[30, 30] | \n\n |
placement | \n弹出位置,可选 tl tr bl br | \nString | \ntopRight | \n\n |
size | \n使用 Message 组件的 | \nString | \nlarge | \n
The component is partially built to support accessibility, but requires additional developer manual Settings to fully support accessibility: upBtnprops and downBtnprops are set up to enable the screen reader to correctly express the specific functions of the buttons. set aria-live
purpose is NumberPicker
component value change, screen reader will be read.
\nimport { NumberPicker } from '@alifd/next';\n\nclass App extends React.Component {\n constructor(props) {\n super(props);\n this.state = {\n value: 0,\n tip: '',\n };\n this.onChange = this.onChange.bind(this);\n }\n onChange(value, e) {\n let num = '';\n if(value >= 0){\n num = value;\n }else {\n num = `negative ${value * -1}`;\n }\n this.setState({\n value: value,\n tip: `${num}`,\n });\n }\n render() {\n const { value, tip } = this.state;\n return (<div>\n <span id=\"a11y-number-picker\" aria-live=\"assertive\" aria-label={tip}></span>\n <NumberPicker type=\"inline\" value={value} onChange={this.onChange} upBtnProps={{'aria-label':'\b\bincreasing button'}} downBtnProps={{'aria-label':'decreasing button'}} aria-labelledby=\"a11y-number-picker\" />\n </div>);\n }\n}\nReactDOM.render(<App/>, mountNode);
组件内置了部分支持无障碍, 但是额外需要开发者手动设置才能完整支持无障碍: 设置upBtnprops以及downBtnprops,使得\b读屏软件可以正确表达按键的具体功能。设置aria-live
目的是NumberPicker
组件值发生改变时,读屏软件会进行读取。
\nimport { NumberPicker } from '@alifd/next';\n\nclass App extends React.Component {\n constructor(props) {\n super(props);\n this.state = {\n value: 0,\n tip: '',\n };\n this.onChange = this.onChange.bind(this);\n }\n onChange(value, e) {\n let num = '';\n if(value >= 0){\n num = value;\n }else {\n num = `negative ${value * -1}`;\n }\n this.setState({\n value: value,\n tip: `${num}`,\n });\n }\n render() {\n const { value, tip } = this.state;\n return (<div>\n <span id=\"a11y-number-picker\" aria-live=\"assertive\" aria-label={tip}></span>\n <NumberPicker type=\"inline\" value={value} onChange={this.onChange} upBtnProps={{'aria-label':'\b\bincreasing button'}} downBtnProps={{'aria-label':'decreasing button'}} aria-labelledby=\"a11y-number-picker\" />\n </div>);\n }\n}\nReactDOM.render(<App/>, mountNode);
you can get event type from onChange function second param e.type
。
if events are triggered by '+' button or '-' button, you can get event type from onChange function third param e.triggerType
.
import { NumberPicker } from '@alifd/next';\n\nfunction onChange(value, e) {\n console.log(value, e.type, e.triggerType);\n}\n\nReactDOM.render(\n <div>\n <NumberPicker onChange={onChange}/>\n <br/><br/>\n <NumberPicker defaultValue={0} type=\"inline\" onChange={onChange}/>\n </div>,\n mountNode\n);
onChange 第二个参数 e.type 可以获取事件类型。
\n如果是点击+
-
触发,可以通过 e.triggerType
获取
import { NumberPicker } from '@alifd/next';\n\nfunction onChange(value, e) {\n console.log(value, e.type, e.triggerType);\n}\n\nReactDOM.render(\n <div>\n <NumberPicker onChange={onChange}/>\n <br/><br/>\n <NumberPicker defaultValue={0} type=\"inline\" onChange={onChange}/>\n </div>,\n mountNode\n);
disable number picker。
\n","order":"6"},"codes":{"jsx":"import { NumberPicker } from '@alifd/next';\n\nReactDOM.render(\nimport { NumberPicker } from '@alifd/next';\n\nReactDOM.render(\n <div>\n <NumberPicker defaultValue={0} disabled/>\n <br/><br/>\n <NumberPicker defaultValue={0} type=\"inline\" disabled />\n </div>,\n mountNode\n);
不可用的 number picker。
\n","order":"6"},"codes":{"jsx":"import { NumberPicker } from '@alifd/next';\n\nReactDOM.render(\nimport { NumberPicker } from '@alifd/next';\n\nReactDOM.render(\n <div>\n <NumberPicker defaultValue={0} disabled/>\n <br/><br/>\n <NumberPicker defaultValue={0} type=\"inline\" disabled />\n </div>,\n mountNode\n);
Forbid directly inputting data, only allow changing data by clicking button
\n","order":"1"},"codes":{"jsx":"import { NumberPicker, Button } from '@alifd/next';\n\n\nclass App extends React.Component {\n constructor(props) {\n super(props);\n this.state = {\n editable: false,\n value: 0\n };\n }\n\n toogle() {\n this.setState({\n editable: !this.state.editable\n });\n }\n\n onChange(value) {\n console.log('changed', value);\n this.setState({\n value: value\n });\n }\n\n render() {\n return (import { NumberPicker, Button } from '@alifd/next';\n\n\nclass App extends React.Component {\n constructor(props) {\n super(props);\n this.state = {\n editable: false,\n value: 0\n };\n }\n\n toogle() {\n this.setState({\n editable: !this.state.editable\n });\n }\n\n onChange(value) {\n console.log('changed', value);\n this.setState({\n value: value\n });\n }\n\n render() {\n return (<div>\n <NumberPicker onChange={this.onChange.bind(this)} value={this.state.value}\n editable={this.state.editable}/><br/><br/>\n <Button onClick={this.toogle.bind(this)}>Toggle to {!this.state.editable ? 'editable' : 'uneditable'}</Button>\n </div>);\n }\n}\nReactDOM.render(<App/>, mountNode);
用户不可直接输入编辑数据
\n","order":"1"},"codes":{"jsx":"import { NumberPicker, Button } from '@alifd/next';\n\n\nclass App extends React.Component {\n constructor(props) {\n super(props);\n this.state = {\n editable: false,\n value: 0\n };\n }\n\n toogle() {\n this.setState({\n editable: !this.state.editable\n });\n }\n\n onChange(value) {\n console.log('changed', value);\n this.setState({\n value: value\n });\n }\n\n render() {\n return (import { NumberPicker, Button } from '@alifd/next';\n\n\nclass App extends React.Component {\n constructor(props) {\n super(props);\n this.state = {\n editable: false,\n value: 0\n };\n }\n\n toogle() {\n this.setState({\n editable: !this.state.editable\n });\n }\n\n onChange(value) {\n console.log('changed', value);\n this.setState({\n value: value\n });\n }\n\n render() {\n return (<div>\n <NumberPicker onChange={this.onChange.bind(this)} value={this.state.value}\n editable={this.state.editable}/><br/><br/>\n <Button onClick={this.toogle.bind(this)}>Toggle to {!this.state.editable ? 'editable' : 'uneditable'}</Button>\n </div>);\n }\n}\nReactDOM.render(<App/>, mountNode);
import { NumberPicker } from '@alifd/next';\n\nconst intlize = val => Intl.NumberFormat('en-US').format(val);\n\nReactDOM.render(\n <div>\n <NumberPicker format={intlize} defaultValue={5000} />\n <br/><br/>\n <NumberPicker label=\"p:\" format={val => `${val}%`} defaultValue={85} />\n <br/><br/>\n <NumberPicker innerAfter=\"%\" />\n </div>,\n mountNode\n);
import { NumberPicker } from '@alifd/next';\n\nconst intlize = val => Intl.NumberFormat('en-US').format(val);\n\nReactDOM.render(\n <div>\n <NumberPicker format={intlize} defaultValue={5000} />\n <br/><br/>\n <NumberPicker label=\"p:\" format={val => `${val}%`} defaultValue={85} />\n <br/><br/>\n <NumberPicker innerAfter=\"%\" />\n </div>,\n mountNode\n);
Use the param min
to limit minimum value,\nUse the param max
to limit maximum value,
That the value exceeds min
or max
will trigger onCorrect.
import { NumberPicker } from '@alifd/next';\n\nfunction onChange(value, e) {\n console.log('onChange', value, e);\n}\n\nfunction onCorrect(obj) {\n console.log('onCorrect', obj);\n}\nReactDOM.render(\n <div>\n <NumberPicker type=\"inline\" step={3} min={6} max={30} defaultValue={6}\n onChange={onChange} onCorrect={onCorrect}/>\n </div>,\n mountNode\n);
min max 来限制value的最大最小值。
\n当数据自动订正会触发 onCorrect
\n","order":"2"},"codes":{"jsx":"import { NumberPicker } from '@alifd/next';\n\nfunction onChange(value, e) {\n console.log('onChange', value, e);\n}\n\nfunction onCorrect(obj) {\n console.log('onCorrect', obj);\n}\nReactDOM.render(\nimport { NumberPicker } from '@alifd/next';\n\nfunction onChange(value, e) {\n console.log('onChange', value, e);\n}\n\nfunction onCorrect(obj) {\n console.log('onCorrect', obj);\n}\nReactDOM.render(\n <div>\n <NumberPicker type=\"inline\" step={3} min={6} max={30} defaultValue={6}\n onChange={onChange} onCorrect={onCorrect}/>\n </div>,\n mountNode\n);
force set type=normal while device=phone
\n","order":"9"},"codes":{"jsx":"import { NumberPicker, Radio } from '@alifd/next';\n\nclass Demo extends React.Component {\n state = {\n device: 'desktop'\n }\n\n handleDeviceChange = (device) => {\n this.setState({\n device\n });\n };\n\n render() {\n return (\nimport { NumberPicker, Radio } from '@alifd/next';\n\nclass Demo extends React.Component {\n state = {\n device: 'desktop'\n }\n\n handleDeviceChange = (device) => {\n this.setState({\n device\n });\n };\n\n render() {\n return (\n <div>\n <Radio.Group\n shape=\"button\"\n value={this.state.device}\n onChange={this.handleDeviceChange}\n >\n <Radio value=\"desktop\">desktop</Radio>\n <Radio value=\"phone\">phone</Radio>\n </Radio.Group>\n <hr/>\n <NumberPicker device={this.state.device}/>\n </div>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
device=phone 下会强制设置 type=normal
\n","order":"9"},"codes":{"jsx":"import { NumberPicker, Radio } from '@alifd/next';\n\nclass Demo extends React.Component {\n state = {\n device: 'desktop'\n }\n\n handleDeviceChange = (device) => {\n this.setState({\n device\n });\n };\n\n render() {\n return (\nimport { NumberPicker, Radio } from '@alifd/next';\n\nclass Demo extends React.Component {\n state = {\n device: 'desktop'\n }\n\n handleDeviceChange = (device) => {\n this.setState({\n device\n });\n };\n\n render() {\n return (\n <div>\n <Radio.Group\n shape=\"button\"\n value={this.state.device}\n onChange={this.handleDeviceChange}\n >\n <Radio value=\"desktop\">desktop</Radio>\n <Radio value=\"phone\">phone</Radio>\n </Radio.Group>\n <hr/>\n <NumberPicker device={this.state.device}/>\n </div>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
Use precision to Control the number of decimal places.
\n","order":"4"},"codes":{"jsx":"import { NumberPicker } from '@alifd/next';\n\nfunction onChange(value) {\n console.log('changed', value);\n}\nfunction onCorrect(obj) {\n console.log(obj);\n}\nReactDOM.render(\nimport { NumberPicker } from '@alifd/next';\n\nfunction onChange(value) {\n console.log('changed', value);\n}\nfunction onCorrect(obj) {\n console.log(obj);\n}\nReactDOM.render(\n <div>\n <NumberPicker defaultValue={-3.99} onChange={onChange} onCorrect={onCorrect} step={2} precision={2}/>\n </div>, mountNode);
通过 precision 控制小数点位数
\n","order":"4"},"codes":{"jsx":"import { NumberPicker } from '@alifd/next';\n\nfunction onChange(value) {\n console.log('changed', value);\n}\nfunction onCorrect(obj) {\n console.log(obj);\n}\nReactDOM.render(\nimport { NumberPicker } from '@alifd/next';\n\nfunction onChange(value) {\n console.log('changed', value);\n}\nfunction onCorrect(obj) {\n console.log(obj);\n}\nReactDOM.render(\n <div>\n <NumberPicker defaultValue={-3.99} onChange={onChange} onCorrect={onCorrect} step={2} precision={2}/>\n </div>, mountNode);
import { NumberPicker } from '@alifd/next';\n\nReactDOM.render(\n <div>\n <NumberPicker defaultValue={0} size=\"large\" />\n <br/><br/>\n <NumberPicker defaultValue={0} size=\"large\" type=\"inline\" />\n </div>,\n mountNode\n);
import { NumberPicker } from '@alifd/next';\n\nReactDOM.render(\n <div>\n <NumberPicker defaultValue={0} size=\"large\" />\n <br/><br/>\n <NumberPicker defaultValue={0} size=\"large\" type=\"inline\" />\n </div>,\n mountNode\n);
Use step to control the number change every click.
\n","order":"3"},"codes":{"jsx":"import { NumberPicker } from '@alifd/next';\n\nfunction onChange(value) {\n console.log('changed', value);\n}\nfunction onCorrect(obj) {\n console.log(obj);\n}\nReactDOM.render(\nimport { NumberPicker } from '@alifd/next';\n\nfunction onChange(value) {\n console.log('changed', value);\n}\nfunction onCorrect(obj) {\n console.log(obj);\n}\nReactDOM.render(\n <div>\n <NumberPicker defaultValue={0} onChange={onChange} onCorrect={onCorrect} step={.01}/>\n </div>, mountNode);
通过step控制每次加减步长
\n","order":"3"},"codes":{"jsx":"import { NumberPicker } from '@alifd/next';\n\nfunction onChange(value) {\n console.log('changed', value);\n}\nfunction onCorrect(obj) {\n console.log(obj);\n}\nReactDOM.render(\nimport { NumberPicker } from '@alifd/next';\n\nfunction onChange(value) {\n console.log('changed', value);\n}\nfunction onCorrect(obj) {\n console.log(obj);\n}\nReactDOM.render(\n <div>\n <NumberPicker defaultValue={0} onChange={onChange} onCorrect={onCorrect} step={.01}/>\n </div>, mountNode);
Number input and auto correct data.
\nauto Correct may change the input value and let it be diffrent with onChange return value。
\nSome interval value may not trigger the onChange, For example:
\n0
=>0.
=>0.0
=>0.01
the second & third step will not trigger onChange, because auto correct will let value always be '0'1
=>12
the step one ,1
, will not not trigger onChange, because the numbers are input one by oneif input action does not trigger onChange, it will correct data and trigger onChange when it gets blur
\nParam | \nDescripiton | \nType | \nDefault Value | \n
---|---|---|---|
size | \nsize option: 'large', 'medium' | \nEnum | \n'medium' | \n
type | \ndisplay type option: 'normal' 'inline' | \nEnum | \n'normal' | \n
value | \ncurrent value | \nNumber | \n- | \n
defaultValue | \ndefault value | \nNumber | \n0 | \n
disabled | \ndisabled or not | \nBoolean | \n- | \n
step | \nnumber changes per click | \nNumber/String | \n1 | \n
precision | \nprecision for decimals number | \nNumber | \n0 | \n
editable | \neditable or not | \nBoolean | \ntrue | \n
autoFocus | \nauto get focused or not | \nBoolean | \n- | \n
onChange | \ncallback when value changes signature: Function(value: Number, e: Event) => void params: value: {Number} data _e_: {Event} DOM Event | \nFunction | \nfunc.noop | \n
onKeyDown | \ncallback when key press signature: Function() => void | \nFunction | \nfunc.noop | \n
onBlur | \ncallback when lose focus signature: Function() => void | \nFunction | \nfunc.noop | \n
onCorrect | \ncallback when data are corrected signature: Function(obj: Object) => void params: obj: {Object} {currentValue,oldValue:String} | \nFunction | \nfunc.noop | \n
max | \nmaximum value | \nNumber | \nInfinity | \n
min | \nminimum value | \nNumber | \n-Infinity | \n
format | \nformat value for display signature: Function(value: Number) => String/Number params: value: {Number} current value return: {String/Number} formatted value | \nFunction | \n- | \n
KeyBoard | \nDescripiton | \n
---|---|
Up Arrow | \nincrease the number | \n
Down Arrow | \ndecrease the number | \n
数字选择器,并对输入的数据做正确性检查、自动订正。
\n自动订正可能会导致onChange返回值和你输入的数据不一样。
\n其中有些中间输入状态无法触发onChange,主要考虑到自动订正可能永远无法到达想要的值了。例如:
\n0
=>0.
=>0.0
=>0.01
中间两步不会触发onChange,因为如果订正会一直停留在0导致永远无法到达想要的值1
=>12
第一步 1
不会触发onChange也不会订正数据,因为数字是一个一个输入的如果输入时没触发onChange,会在onBlur检测数据正确性并触发onChange
\n参数 | \n说明 | \n类型 | \n默认值 | \n
---|---|---|---|
size | \n大小 可选值: 'large', 'medium' | \nEnum | \n'medium' | \n
type | \n设置类型 可选值: 'normal'(普通) 'inline'(内联) | \nEnum | \n'normal' | \n
value | \n当前值 | \nNumber | \n- | \n
defaultValue | \n默认值 | \nNumber | \n- | \n
disabled | \n是否禁用 | \nBoolean | \n- | \n
step | \n步长 | \nNumber/String | \n1 | \n
precision | \n保留小数点后位数 | \nNumber | \n0 | \n
editable | \n用户是否可以输入 | \nBoolean | \ntrue | \n
autoFocus | \n自动焦点 | \nBoolean | \n- | \n
onChange | \n数值被改变的事件 签名: Function(value: Number, e: Event) => void 参数: value: {Number} 数据 _e_: {Event} DOM事件对象 | \nFunction | \nfunc.noop | \n
onKeyDown | \n键盘按下 签名: Function() => void | \nFunction | \nfunc.noop | \n
onFocus | \n焦点获得 签名: Function() => void | \nFunction | \n- | \n
onBlur | \n焦点失去 签名: Function() => void | \nFunction | \nfunc.noop | \n
onCorrect | \n数值订正后的回调 签名: Function(obj: Object) => void 参数: obj: {Object} {currentValue,oldValue:String} | \nFunction | \nfunc.noop | \n
max | \n最大值 | \nNumber | \nInfinity | \n
min | \n最小值 | \nNumber | \n-Infinity | \n
format | \n格式化当前值 签名: Function(value: Number) => String/Number 参数: value: {Number} null 返回值: {String/Number} null | \nFunction | \n- | \n
upBtnProps | \n增加按钮的props | \nObject | \n- | \n
downBtnProps | \n减少按钮的props | \nObject | \n- | \n
label | \n内联 label | \nReactNode | \n- | \n
innerAfter | \ninner after | \nReactNode | \n- | \n
device | \n预设屏幕宽度 可选值: 'phone', 'tablet', 'desktop' | \nEnum | \n- | \n
按键 | \n说明 | \n
---|---|
Up Arrow | \n数字增加 | \n
Down Arrow | \n数字减小 | \n
Use align prop to set align type
\n","order":"6"},"codes":{"jsx":"import { Overlay } from '@alifd/next';\n\nconst { Popup } = Overlay;\n\nReactDOM.render(\n.overlay-container {\n position: relative;\n height: 150px;\n margin: 50px;\n border: 1px solid #999;\n overflow: auto;\n text-align: center;\n color: red;\n}
import { Overlay } from '@alifd/next';\n\nconst { Popup } = Overlay;\n\nReactDOM.render(\n <div >\n <div id=\"container1\" className=\"overlay-container\">\n normal example\n <Overlay target=\"container1\" visible align=\"tr tr\"><span>123</span></Overlay>\n <Overlay target=\"container1\" visible align=\"cc cr\"><span>123</span></Overlay>\n <Overlay target=\"container1\" visible align=\"bc bc\"><span>123</span></Overlay>\n </div>\n <br /><br /><br /><br />\n <div id=\"container2\" className=\"overlay-container\" dir=\"rtl\">\n dir=rtl example\n <Overlay target=\"container2\" rtl visible align=\"tr tr\"><span>123</span></Overlay>\n <Overlay target=\"container2\" rtl visible align=\"cc cr\"><span>123</span></Overlay>\n <Overlay target=\"container2\" rtl visible align=\"bc bc\"><span>123</span></Overlay>\n </div>\n </div>\n , mountNode);
可以自定义对齐方式
\n","order":"6"},"codes":{"jsx":"import { Overlay } from '@alifd/next';\n\nconst { Popup } = Overlay;\n\nReactDOM.render(\n.overlay-container {\n position: relative;\n height: 150px;\n margin: 50px;\n border: 1px solid #999;\n overflow: auto;\n text-align: center;\n color: red;\n}
import { Overlay } from '@alifd/next';\n\nconst { Popup } = Overlay;\n\nReactDOM.render(\n <div >\n <div id=\"container1\" className=\"overlay-container\">\n normal example\n <Overlay target=\"container1\" visible align=\"tr tr\"><span>123</span></Overlay>\n <Overlay target=\"container1\" visible align=\"cc cr\"><span>123</span></Overlay>\n <Overlay target=\"container1\" visible align=\"bc bc\"><span>123</span></Overlay>\n </div>\n <br /><br /><br /><br />\n <div id=\"container2\" className=\"overlay-container\" dir=\"rtl\">\n dir=rtl example\n <Overlay target=\"container2\" rtl visible align=\"tr tr\"><span>123</span></Overlay>\n <Overlay target=\"container2\" rtl visible align=\"cc cr\"><span>123</span></Overlay>\n <Overlay target=\"container2\" rtl visible align=\"bc bc\"><span>123</span></Overlay>\n </div>\n </div>\n , mountNode);
The overlay with mask.
\n","order":"1"},"codes":{"jsx":"import { Overlay } from '@alifd/next';\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n visible: false\n };\n }\n\n onClick = () => {\n this.setState({\n visible: true\n });\n }\n\n onClose = () => {\n this.setState({\n visible: false\n });\n }\n\n render() {\n return (\nimport { Overlay } from '@alifd/next';\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n visible: false\n };\n }\n\n onClick = () => {\n this.setState({\n visible: true\n });\n }\n\n onClose = () => {\n this.setState({\n visible: false\n });\n }\n\n render() {\n return (\n <div>\n <button onClick={this.onClick} ref={ref => {\n this.btn = ref;\n }}>\n Open\n </button>\n <Overlay visible={this.state.visible}\n safeNode={() => this.btn}\n align=\"cc cc\"\n hasMask\n disableScroll\n onRequestClose={this.onClose}>\n <span className=\"overlay-demo\">\n Hello World From Overlay!\n </span>\n </Overlay>\n </div>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
.overlay-demo {\n width: 300px;\n height: 100px;\n padding: 10px;\n border: 1px solid #999999;\n background: #FFFFFF;\n box-shadow: 2px 2px 20px rgba(0,0,0,0.15);\n}
带有遮罩的弹层。
\n","order":"1"},"codes":{"jsx":"import { Overlay } from '@alifd/next';\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n visible: false\n };\n }\n\n onClick = () => {\n this.setState({\n visible: true\n });\n }\n\n onClose = () => {\n this.setState({\n visible: false\n });\n }\n\n render() {\n return (\nimport { Overlay } from '@alifd/next';\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n visible: false\n };\n }\n\n onClick = () => {\n this.setState({\n visible: true\n });\n }\n\n onClose = () => {\n this.setState({\n visible: false\n });\n }\n\n render() {\n return (\n <div>\n <button onClick={this.onClick} ref={ref => {\n this.btn = ref;\n }}>\n Open\n </button>\n <Overlay visible={this.state.visible}\n safeNode={() => this.btn}\n align=\"cc cc\"\n hasMask\n disableScroll\n onRequestClose={this.onClose}>\n <span className=\"overlay-demo\">\n Hello World From Overlay!\n </span>\n </Overlay>\n </div>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
.overlay-demo {\n width: 300px;\n height: 100px;\n padding: 10px;\n border: 1px solid #999999;\n background: #FFFFFF;\n box-shadow: 2px 2px 20px rgba(0,0,0,0.15);\n}
Demos Popup under control usage.
\n","order":"3"},"codes":{"jsx":"import { Overlay } from '@alifd/next';\n\nconst { Popup } = Overlay;\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n visible: false\n };\n }\n\n onVisibleChange = visible => {\n this.setState({\n visible\n });\n }\n\n onGroupVisibleChange = groupVisible => {\n this.setState({\n groupVisible\n });\n }\n\n render() {\n return (\nimport { Overlay } from '@alifd/next';\n\nconst { Popup } = Overlay;\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n visible: false\n };\n }\n\n onVisibleChange = visible => {\n this.setState({\n visible\n });\n }\n\n onGroupVisibleChange = groupVisible => {\n this.setState({\n groupVisible\n });\n }\n\n render() {\n return (\n <div>\n <div>\n <Popup trigger={<button>Open</button>}\n triggerType=\"click\"\n visible={this.state.visible}\n onVisibleChange={this.onVisibleChange}>\n <span className=\"overlay-demo\">\n Hello World From Popup!\n </span>\n </Popup>\n </div>\n <br />\n <div>\n <Popup trigger={<button style={{\"margin-right\": \"50px\"}} ref={ref => {this.btn1 = ref;}}>Paired Popup 1</button>}\n triggerType=\"click\"\n visible={this.state.groupVisible}\n safeNode={[() => this.btn2, () => this.overlay2]}\n onVisibleChange={this.onGroupVisibleChange}>\n <span className=\"overlay-demo\" ref={ref => {this.overlay1 = ref;}}>\n Hello World From Popup!\n </span>\n </Popup>\n <Popup trigger={<button ref={ref => {this.btn2 = ref;}}>Paired Popup 2</button>}\n triggerType=\"click\"\n visible={this.state.groupVisible}\n safeNode={[() => this.btn1, () => this.overlay1]}\n onVisibleChange={this.onGroupVisibleChange}> \n <span className=\"overlay-demo\" ref={ref => {this.overlay2 = ref;}}>\n Hello World From Popup!\n </span>\n </Popup>\n </div>\n </div>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
.overlay-demo {\n width: 300px;\n height: 100px;\n padding: 10px;\n border: 1px solid #999999;\n background: #FFFFFF;\n box-shadow: 2px 2px 20px rgba(0,0,0,0.15);\n}
展示了 Popup 受控显示隐藏的用法。
\n","order":"3"},"codes":{"jsx":"import { Overlay } from '@alifd/next';\n\nconst { Popup } = Overlay;\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n visible: false\n };\n }\n\n onVisibleChange = visible => {\n this.setState({\n visible\n });\n }\n\n onGroupVisibleChange = groupVisible => {\n this.setState({\n groupVisible\n });\n }\n\n render() {\n return (\nimport { Overlay } from '@alifd/next';\n\nconst { Popup } = Overlay;\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n visible: false\n };\n }\n\n onVisibleChange = visible => {\n this.setState({\n visible\n });\n }\n\n onGroupVisibleChange = groupVisible => {\n this.setState({\n groupVisible\n });\n }\n\n render() {\n return (\n <div>\n <div>\n <Popup trigger={<button>Open</button>}\n triggerType=\"click\"\n visible={this.state.visible}\n onVisibleChange={this.onVisibleChange}>\n <span className=\"overlay-demo\">\n Hello World From Popup!\n </span>\n </Popup>\n </div>\n <br />\n <div>\n <Popup trigger={<button style={{\"margin-right\": \"50px\"}} ref={ref => {this.btn1 = ref;}}>Paired Popup 1</button>}\n triggerType=\"click\"\n visible={this.state.groupVisible}\n safeNode={[() => this.btn2, () => this.overlay2]}\n onVisibleChange={this.onGroupVisibleChange}>\n <span className=\"overlay-demo\" ref={ref => {this.overlay1 = ref;}}>\n Hello World From Popup!\n </span>\n </Popup>\n <Popup trigger={<button ref={ref => {this.btn2 = ref;}}>Paired Popup 2</button>}\n triggerType=\"click\"\n visible={this.state.groupVisible}\n safeNode={[() => this.btn1, () => this.overlay1]}\n onVisibleChange={this.onGroupVisibleChange}> \n <span className=\"overlay-demo\" ref={ref => {this.overlay2 = ref;}}>\n Hello World From Popup!\n </span>\n </Popup>\n </div>\n </div>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
.overlay-demo {\n width: 300px;\n height: 100px;\n padding: 10px;\n border: 1px solid #999999;\n background: #FFFFFF;\n box-shadow: 2px 2px 20px rgba(0,0,0,0.15);\n}
When there is a overlay nesting requirement, use the container property to render the second overlay inside the first overlay.
\n","order":"4"},"codes":{"jsx":"import { Overlay } from '@alifd/next';\n\nconst { Popup } = Overlay;\n\nReactDOM.render(\nHello World From Second Overlay!
\nHello World From First Overlay!
\nHello World From Second Overlay!
\nHello World From First Overlay!
\nimport { Overlay } from '@alifd/next';\n\nconst { Popup } = Overlay;\n\nReactDOM.render(\n <Popup trigger={<button>Open first overlay</button>}\n triggerType=\"click\">\n <div className=\"overlay-demo\">\n <Popup trigger={<button>Open second overlay</button>}\n triggerType=\"click\"\n container={trigger => trigger.parentNode}>\n <div className=\"overlay-demo\">\n <p>Hello World From Second Overlay!</p>\n </div>\n </Popup>\n <p>Hello World From First Overlay!</p>\n </div>\n </Popup>\n , mountNode);
.overlay-demo {\n width: 300px;\n height: 100px;\n padding: 10px;\n border: 1px solid #999999;\n background: #FFFFFF;\n box-shadow: 2px 2px 20px rgba(0,0,0,0.15);\n}
有弹层嵌套需求时,请使用 container 属性将第二个弹层渲染到第一个弹层内部。
\n","order":"4"},"codes":{"jsx":"import { Overlay } from '@alifd/next';\n\nconst { Popup } = Overlay;\n\nReactDOM.render(\nHello World From Second Overlay!
\nHello World From First Overlay!
\nHello World From Second Overlay!
\nHello World From First Overlay!
\nimport { Overlay } from '@alifd/next';\n\nconst { Popup } = Overlay;\n\nReactDOM.render(\n <Popup trigger={<button>Open first overlay</button>}\n triggerType=\"click\">\n <div className=\"overlay-demo\">\n <Popup trigger={<button>Open second overlay</button>}\n triggerType=\"click\"\n container={trigger => trigger.parentNode}>\n <div className=\"overlay-demo\">\n <p>Hello World From Second Overlay!</p>\n </div>\n </Popup>\n <p>Hello World From First Overlay!</p>\n </div>\n </Popup>\n , mountNode);
.overlay-demo {\n width: 300px;\n height: 100px;\n padding: 10px;\n border: 1px solid #999999;\n background: #FFFFFF;\n box-shadow: 2px 2px 20px rgba(0,0,0,0.15);\n}
Pop up a overlay.
\n","order":"0"},"codes":{"jsx":"import { Overlay } from '@alifd/next';\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n visible: false\n };\n }\n\n onClick = () => {\n this.setState({\n visible: !this.state.visible\n });\n }\n\n onClose = () => {\n this.setState({\n visible: false\n });\n }\n\n render() {\n return (\nimport { Overlay } from '@alifd/next';\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n visible: false\n };\n }\n\n onClick = () => {\n this.setState({\n visible: !this.state.visible\n });\n }\n\n onClose = () => {\n this.setState({\n visible: false\n });\n }\n\n render() {\n return (\n <div>\n <button onClick={this.onClick} ref={ref => {\n this.btn = ref;\n }}>\n Toggle visible\n </button>\n <Overlay visible={this.state.visible}\n target={() => this.btn}\n safeNode={() => this.btn}\n onRequestClose={this.onClose}>\n <span className=\"overlay-demo\">\n Hello World From Overlay!\n </span>\n </Overlay>\n </div>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
.overlay-demo {\n width: 300px;\n height: 100px;\n padding: 10px;\n border: 1px solid #999999;\n background: #FFFFFF;\n box-shadow: 2px 2px 20px rgba(0,0,0,0.15);\n}
弹出一个弹层。
\n","order":"0"},"codes":{"jsx":"import { Overlay } from '@alifd/next';\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n visible: false\n };\n }\n\n onClick = () => {\n this.setState({\n visible: !this.state.visible\n });\n }\n\n onClose = () => {\n this.setState({\n visible: false\n });\n }\n\n render() {\n return (\nimport { Overlay } from '@alifd/next';\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n visible: false\n };\n }\n\n onClick = () => {\n this.setState({\n visible: !this.state.visible\n });\n }\n\n onClose = () => {\n this.setState({\n visible: false\n });\n }\n\n render() {\n return (\n <div>\n <button onClick={this.onClick} ref={ref => {\n this.btn = ref;\n }}>\n Toggle visible\n </button>\n <Overlay visible={this.state.visible}\n target={() => this.btn}\n safeNode={() => this.btn}\n onRequestClose={this.onClose}>\n <span className=\"overlay-demo\">\n Hello World From Overlay!\n </span>\n </Overlay>\n </div>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
.overlay-demo {\n width: 300px;\n height: 100px;\n padding: 10px;\n border: 1px solid #999999;\n background: #FFFFFF;\n box-shadow: 2px 2px 20px rgba(0,0,0,0.15);\n}
Use popup to pop up a overlay.
\n","order":"2"},"codes":{"jsx":"import { Overlay } from '@alifd/next';\n\nconst { Popup } = Overlay;\n\nReactDOM.render(\nimport { Overlay } from '@alifd/next';\n\nconst { Popup } = Overlay;\n\nReactDOM.render(\n <div>\n <Popup trigger={<button>Open</button>} triggerType=\"click\">\n <span className=\"overlay-demo\">\n Hello World From Popup!\n </span>\n </Popup>\n <br />\n <Popup trigger={<button>Use Down Arrow to open</button>} triggerType=\"click\" triggerClickKeycode={40}>\n <span className=\"overlay-demo\">\n Hello World From Popup!\n </span>\n </Popup>\n </div>\n , mountNode);
.overlay-demo {\n width: 300px;\n height: 100px;\n padding: 10px;\n border: 1px solid #999999;\n background: #FFFFFF;\n box-shadow: 2px 2px 20px rgba(0,0,0,0.15);\n}
使用 Popup 弹出一个弹层。
\n","order":"2"},"codes":{"jsx":"import { Overlay } from '@alifd/next';\n\nconst { Popup } = Overlay;\n\nReactDOM.render(\nimport { Overlay } from '@alifd/next';\n\nconst { Popup } = Overlay;\n\nReactDOM.render(\n <div>\n <Popup trigger={<button>Open</button>} triggerType=\"click\">\n <span className=\"overlay-demo\">\n Hello World From Popup!\n </span>\n </Popup>\n <br />\n <Popup trigger={<button>Use Down Arrow to open</button>} triggerType=\"click\" triggerClickKeycode={40}>\n <span className=\"overlay-demo\">\n Hello World From Popup!\n </span>\n </Popup>\n </div>\n , mountNode);
.overlay-demo {\n width: 300px;\n height: 100px;\n padding: 10px;\n border: 1px solid #999999;\n background: #FFFFFF;\n box-shadow: 2px 2px 20px rgba(0,0,0,0.15);\n}
The overlay defaults to absolute positioning with reference to document.body. If the overlay trigger element's container (usually the parent node) has a scrollbar, then when the container is scrolled, the trigger element will be separated from the overlay. The solution is to render the overlay to the container where the trigger element is located. (The container must have a position style to support the absolute positioning of the overlay.)
\n","order":"5"},"codes":{"jsx":"import { Overlay } from '@alifd/next';\n\nconst { Popup } = Overlay;\n\nReactDOM.render(\nimport { Overlay } from '@alifd/next';\n\nconst { Popup } = Overlay;\n\nReactDOM.render(\n <div className=\"scroll-container\">\n <Popup trigger={<button>Open</button>}\n triggerType=\"click\"\n container={trigger => trigger.parentNode}>\n <div className=\"overlay-demo\">\n Hello World From Popup!\n </div>\n </Popup>\n <div style={{ height: '300px' }} />\n </div>\n , mountNode);
.overlay-demo {\n width: 300px;\n height: 100px;\n padding: 10px;\n border: 1px solid #999999;\n background: #FFFFFF;\n box-shadow: 2px 2px 20px rgba(0,0,0,0.15);\n}\n\n.scroll-container {\n position: relative;\n height: 150px;\n padding: 10px;\n border: 1px solid #999999;\n overflow: auto;\n}
弹层默认参照 document.body 绝对定位,如果弹层显示隐藏的触发元素所在容器(一般为父节点)有滚动条,那么当容器滚动时,会发生触发元素与弹层相分离的情况,解决的办法是将弹层渲染到触发元素所在的容器中。(触发元素所在的容器,必须设置 position 样式,以完成弹层的绝对定位。)
\n","order":"5"},"codes":{"jsx":"import { Overlay } from '@alifd/next';\n\nconst { Popup } = Overlay;\n\nReactDOM.render(\nimport { Overlay } from '@alifd/next';\n\nconst { Popup } = Overlay;\n\nReactDOM.render(\n <div className=\"scroll-container\">\n <Popup trigger={<button>Open</button>}\n triggerType=\"click\"\n container={trigger => trigger.parentNode}>\n <div className=\"overlay-demo\">\n Hello World From Popup!\n </div>\n </Popup>\n <div style={{ height: '300px' }} />\n </div>\n , mountNode);
.overlay-demo {\n width: 300px;\n height: 100px;\n padding: 10px;\n border: 1px solid #999999;\n background: #FFFFFF;\n box-shadow: 2px 2px 20px rgba(0,0,0,0.15);\n}\n\n.scroll-container {\n position: relative;\n height: 150px;\n padding: 10px;\n border: 1px solid #999999;\n overflow: auto;\n}
A collection of tool for generating overlay.
\nOverlay provides a series of components for creating overlay:
\nOverlay can pop up a layer in the page, provides positioning, animation and other common functions. Overlay is designed as a stateless component that does not control the state of its own visible.
\nNote: Configurations like canCloseby* also need to work with onRequestClose to close the overlay.
\nOverlay provides the function of hiding itself by clicking document. If you want to click a node and do not hide the overlay (for example, the node that triggers the overlay to open), pass the node to the safeNode property.
\nThe value of the align property can be a space-separated string, such as tl bl
, tl
means the top left of the target element and bl
means the bottom left of the reference element, so tl bl
means the top left of the target element aligns with the bottom left of the reference element. Among the available options are tl
, tc
, tr
, cl
, cc
, cr
, bl
, bc
, br
. t
is short for top
, b
is short for bottom
, c
is short for center
, l
is short for left
, and r
is short for right
.
The align support Boolean value is only false. When set to false, JS positioning is not used, so you can pass the style or className for CSS positioning according to your needs.
\nUnder RTL Mode, Overylay will transfer r(right) and l(left) to each other automatically. It means tl bl
under RTL Mode works the same to tr br
under Non-RTL Mode\nThe following example shows how to position the overlay to the top right corner of the page:
<Overlay visible align="tr tr"><span>123</span></Overlay>
Popup is the wrapper of Overlay. It receives a node as a trigger node and pops up a overlay. This overlay uses the node as the reference element for positioning by default.
\nParam | \nDescripiton | \nType | \nDefault Value | \n
---|---|---|---|
children | \nconent of overlay | \nany | \n- | \n
visible | \nwhether to show the overlay | \nBoolean | \nfalse | \n
onRequestClose | \ncallback function that triggers an event when the overlay request closed signatures: Function(type: String, e: Object) => void params: type: {String} the reason of the overlay closure _e_: {Object} DOM event | \nFunction | \nfunc.noop | \n
target | \nreference element for overlay positioning | \nany | \nPosition.VIEWPORT | \n
align | \nalignment of the overlay relative to the reference element, see Alignment | \nString/Boolean | \n'tl bl' | \n
offset | \nextra adjustment for trigger element. e.g. [hoz, ver] means move to right ${hoz}px (to left in RTL mode), to bottom ${ver}px | \nArray | \n[0, 0] | \n
container | \ncontainer of the overlay, if it is a function, it should return ref, if it is a string, it is should be the id of the DOM element, it can also be passed the DOM element directly. | \nany | \n- | \n
hasMask | \nwhether to show the mask | \nBoolean | \nfalse | \n
canCloseByEsc | \nwhether to support pressing esc to close the overlay | \nBoolean | \ntrue | \n
canCloseByOutSideClick | \nwhether to support clicking the outside to close the overlay when the mask is hidden | \nBoolean | \ntrue | \n
canCloseByMask | \nwhether to support clicking the mask to close the overlay when the mask is visible | \nBoolean | \ntrue | \n
beforeOpen | \ncallback function that triggers the event before the overlay opens signatures: Function() => void | \nFunction | \nfunc.noop | \n
onOpen | \ncallback function that triggers the event when the overlay opens signatures: Function() => void | \nFunction | \nfunc.noop | \n
afterOpen | \ncallback function that triggers the event after the overlay opens, if enable animations, trigger after the animation ends signatures: Function() => void | \nFunction | \nfunc.noop | \n
beforeClose | \ncallback function that triggers the event before the overlay closes signatures: Function() => void | \nFunction | \nfunc.noop | \n
onClose | \ncallback function that triggers the event when the overlay closes signatures: Function() => void | \nFunction | \nfunc.noop | \n
afterClose | \ncallback function that triggers the event after the overlay closes, if enable animations, trigger after the animation ends signatures: Function() => void | \nFunction | \nfunc.noop | \n
beforePosition | \ncallback function that triggers the event before the overlay posiitons signatures: Function() => void | \nFunction | \nfunc.noop | \n
onPosition | \ncallback function that triggers the event when the overlay posiitons signatures: Function(config: Object, node: Object) => void params: config: {Object} position arguments config.align: {Array} alignment, such as ['cc', 'cc'] (if you enable needAdjust, it may be different from pre-set align) config.top: {Number} distance from the top of the viewport config.left: {Number} distance from the left of the viewport node: {Object} container node | \nFunction | \nfunc.noop | \n
shouldUpdatePosition | \nwhether to force the update of positioning after each rerendered, which is generally used to maintain the original positioning when the size of the content area changes. | \nBoolean | \nfalse | \n
autoFocus | \nwhether to focus the element in the overlay automatically when the overlay is opened | \nBoolean | \nfalse | \n
needAdjust | \nwhen the overlay is not visible due to scrolling of the page, does it automatically adjust the position to appear in the visible area? | \nBoolean | \ntrue | \n
disableScroll | \nwhether to disable page scrolling | \nBoolean | \nfalse | \n
cache | \nwhether to keep dom nodes when hidden | \nBoolean | \nfalse | \n
safeNode | \nwhen clicking on the document, does not close the overlay if the node is included. If it is a function, it should return ref, if it is a string, it should be the id of the DOM element, it can also be directly passed to the DOM element, or the above values Array | \nany | \n- | \n
wrapperClassName | \nclass name of the overlay's wrapper node | \nString | \n- | \n
wrapperStyle | \ninline stylesheet of the overlay's wrapper node | \nObject | \n- | \n
animation | \nconfigure animation, support the {in: 'enter-class', out: 'leave-class' } object parameters, if set to false, do not play the animation. Refer to Animate component documentation for available animations. | \nObject/Boolean | \n{ in: 'expandInDown', out: 'expandOutUp' } | \n
\n\nInherited Overlay's API unless otherwise specified
\n
Param | \nDescripiton | \nType | \nDefault Value | \n
---|---|---|---|
children | \ncontent of overlay | \nReactNode | \n- | \n
trigger | \ntrigger the overlay to show or hide elements | \nReactElement | \n- | \n
triggerType | \ntrigger the overlay to show or hide operations, either 'click', 'hover', 'focus', or an array of them, such as ['hover', 'focus'] | \nString/Array | \n'hover' | \n
triggerClickKeycode | \nCustomize the keyboard trigger keys that will trigger click event handlers when trigger is focused. It will only take effect when the triggerType is 'click'. | \nNumber/Array | \n[KEYCODE.SPACE, KEYCODE.ENTER] | \n
visible | \nwhether the overlay is visiible currently | \nBoolean | \n- | \n
defaultVisible | \nwhether the overlay is visiible default | \nBoolean | \nfalse | \n
onVisibleChange | \ncallback function triggered when the ovlery is visible or hidden signatures: Function(visible: Boolean, type: String, e: Object) => void params: visible: {Boolean} whether the overlay is visible type: {String} the reason that triggers the overlay to show or hide _e_: {Object} DOM event | \nFunction | \nfunc.noop | \n
disabled | \nif set this property, the overlay cannot be shown or hidden | \nBoolean | \nfalse | \n
delay | \nThe delay time, in milliseconds, that the overlay shows or hides and only works when triggerType is set to hover | \nNumber | \n200 | \n
canCloseByTrigger | \nwhether the trigger element can close the overlay | \nBoolean | \ntrue | \n
target | \nreference element for overlay positioning | \nany | \ntrigger element | \n
followTrigger | \nfollow trigger to scroll or not | \nBoolean | \nfalse | \n
Description
: This component needs to be used in conjunction with other components to be prompted. Refer to the above overlay
用于生成弹层的工具类集合.
\nOverlay 提供了一系列组件用于创建弹层。其中包含:
\nOverlay 可以在页面中弹出一个浮层,封装了定位,动画及其他一些可用性的功能。Overlay 被设计为无状态的组件,其本身并不控制自己显示和隐藏的状态。
\n注意: 类似 canCloseby* 的配置也需要配合 onRequestClose 才能关闭弹层。
\nOverlay 提供了点击弹层外文档中节点隐藏该弹层的功能,如果想让某个节点点击后不隐藏弹层(如:触发弹层打开的节点),请将该节点传入 safeNode 属性。
\nalign 的值可以是由空格隔开的字符串,如 tl bl
,其中 tl
代表目标元素的左上方,bl
代表基准元素的左下方,所以 tl bl
的意思是目标元素的左上方对齐基准元素左下方。其中定位的可选值有 tl
, tc
, tr
, cl
, cc
, cr
, bl
, bc
, br
。t
为 top
的缩写,b
为 bottom
的缩写,c
为 center
的缩写,l
为 left
的缩写,r
为 right
的缩写.
align 支持的 Boolean 值仅为 false,在设置为 false 时,不使用 JS 定位,这样你可以根据你的需要传入 style 或者 className 进行 CSS 定位。
\nrtl情况下会自动翻转 r(right)与 l(left), 例如 rtl状态下tl bl
与 非rtl状态下tr br
等效\n下面的例子演示了如何将弹层定位到页面的右上角:
<Overlay visible align="tr tr"><span>123</span></Overlay>
Popup 是对 Overlay 的封装,它接收某个节点作为触发节点,弹出一个浮层,这个浮层默认情况下使用这个节点作为定位的参照对象。
\n参数 | \n说明 | \n类型 | \n默认值 | \n
---|---|---|---|
children | \n弹层内容 | \nany | \n- | \n
visible | \n是否显示弹层 | \nBoolean | \nfalse | \n
onRequestClose | \n弹层请求关闭时触发事件的回调函数 签名: Function(type: String, e: Object) => void 参数: type: {String} 弹层关闭的来源 _e_: {Object} DOM 事件 | \nFunction | \nfunc.noop | \n
target | \n弹层定位的参照元素 | \nany | \nPosition.VIEWPORT | \n
align | \n弹层相对于参照元素的定位, 详见开发指南的定位部分 | \nString/Boolean | \n'tl bl' | \n
offset | \n弹层相对于trigger的定位的微调, 接收数组[hoz, ver], 表示弹层在 left / top 上的增量 e.g. [100, 100] 表示往右(RTL 模式下是往左) 、下分布偏移100px | \nArray | \n[0, 0] | \n
container | \n渲染组件的容器,如果是函数需要返回 ref,如果是字符串则是该 DOM 的 id,也可以直接传入 DOM 节点 | \nany | \n- | \n
hasMask | \n是否显示遮罩 | \nBoolean | \nfalse | \n
canCloseByEsc | \n是否支持 esc 按键关闭弹层 | \nBoolean | \ntrue | \n
canCloseByOutSideClick | \n点击弹层外的区域是否关闭弹层,不显示遮罩时生效 | \nBoolean | \ntrue | \n
canCloseByMask | \n点击遮罩区域是否关闭弹层,显示遮罩时生效 | \nBoolean | \ntrue | \n
beforeOpen | \n弹层打开前触发事件的回调函数 签名: Function() => void | \nFunction | \nfunc.noop | \n
onOpen | \n弹层打开时触发事件的回调函数 签名: Function() => void | \nFunction | \nfunc.noop | \n
afterOpen | \n弹层打开后触发事件的回调函数, 如果有动画,则在动画结束后触发 签名: Function() => void | \nFunction | \nfunc.noop | \n
beforeClose | \n弹层关闭前触发事件的回调函数 签名: Function() => void | \nFunction | \nfunc.noop | \n
onClose | \n弹层关闭时触发事件的回调函数 签名: Function() => void | \nFunction | \nfunc.noop | \n
afterClose | \n弹层关闭后触发事件的回调函数, 如果有动画,则在动画结束后触发 签名: Function() => void | \nFunction | \nfunc.noop | \n
beforePosition | \n弹层定位完成前触发的事件 签名: Function() => void | \nFunction | \nfunc.noop | \n
onPosition | \n弹层定位完成时触发的事件 签名: Function(config: Object, node: Object) => void 参数: config: {Object} 定位的参数 config.align: {Array} 对齐方式,如 ['cc', 'cc'](如果开启 needAdjust,可能和预先设置的 align 不同) config.top: {Number} 距离视口顶部距离 config.left: {Number} 距离视口左侧距离 node: {Object} 定位参照的容器节点 | \nFunction | \nfunc.noop | \n
shouldUpdatePosition | \n是否在每次弹层重新渲染后强制更新定位信息,一般用于弹层内容区域大小发生变化时,仍需保持原来的定位方式 | \nBoolean | \nfalse | \n
autoFocus | \n弹层打开时是否让其中的元素自动获取焦点 | \nBoolean | \nfalse | \n
needAdjust | \n当弹层由于页面滚动等情况不在可视区域时,是否自动调整定位以出现在可视区域 | \nBoolean | \ntrue | \n
disableScroll | \n是否禁用页面滚动 | \nBoolean | \nfalse | \n
cache | \n隐藏时是否保留子节点 | \nBoolean | \nfalse | \n
safeNode | \n安全节点,当点击 document 的时候,如果包含该节点则不会关闭弹层,如果是函数需要返回 ref,如果是字符串则是该 DOM 的 id,也可以直接传入 DOM 节点,或者以上值组成的数组 | \nany | \n- | \n
wrapperClassName | \n弹层的根节点的样式类 | \nString | \n- | \n
wrapperStyle | \n弹层的根节点的内联样式 | \nObject | \n- | \n
animation | \n配置动画的播放方式,支持 { in: 'enter-class', out: 'leave-class' } 的对象参数,如果设置为 false,则不播放动画。 请参考 Animate 组件的文档获取可用的动画名 | \nObject/Boolean | \n{ in: 'expandInDown', out: 'expandOutUp' } | \n
\n\n继承 Overlay 的 API,除非特别说明
\n
参数 | \n说明 | \n类型 | \n默认值 | \n
---|---|---|---|
children | \n弹层内容 | \nReactNode | \n- | \n
trigger | \n触发弹层显示或隐藏的元素 | \nReactElement | \n- | \n
triggerType | \n触发弹层显示或隐藏的操作类型,可以是 'click','hover','focus',或者它们组成的数组,如 ['hover', 'focus'] | \nString/Array | \n'hover' | \n
triggerClickKeycode | \n当 triggerType 为 click 时才生效,可自定义触发弹层显示的键盘码 | \nNumber/Array | \n[KEYCODE.SPACE, KEYCODE.ENTER] | \n
visible | \n弹层当前是否显示 | \nBoolean | \n- | \n
defaultVisible | \n弹层默认是否显示 | \nBoolean | \nfalse | \n
onVisibleChange | \n弹层显示或隐藏时触发的回调函数 签名: Function(visible: Boolean, type: String, e: Object) => void 参数: visible: {Boolean} 弹层是否显示 type: {String} 触发弹层显示或隐藏的来源 fromTrigger 表示由trigger的点击触发; docClick 表示由document的点击触发 _e_: {Object} DOM事件 | \nFunction | \nfunc.noop | \n
disabled | \n设置此属性,弹层无法显示或隐藏 | \nBoolean | \nfalse | \n
delay | \n弹层显示或隐藏的延时时间(以毫秒为单位),在 triggerType 被设置为 hover 时生效 | \nNumber | \n200 | \n
canCloseByTrigger | \ntrigger 是否可以关闭弹层 | \nBoolean | \ntrue | \n
target | \n弹层定位的参照元素 | \nany | \ntarget 属性,即触发元素 | \n
followTrigger | \n是否跟随trigger滚动 | \nBoolean | \nfalse | \n
说明
: 此组件需要结合其他组件使用,会有提示。参考上文无障碍
。
import { Pagination } from '@alifd/next';\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n current: 2\n };\n\n this.handleChange = this.handleChange.bind(this);\n }\n\n handleChange(current) {\n this.setState({\n current\n });\n }\n\n render() {\n return (\n <Pagination current={this.state.current} onChange={this.handleChange} />\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
受控分页,是指分页组件的状态由父组件维护,组件自身只负责渲染其父组件传递的值,父组件通过 current
属性传递当前的值。
import { Pagination } from '@alifd/next';\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n current: 2\n };\n\n this.handleChange = this.handleChange.bind(this);\n }\n\n handleChange(current) {\n this.setState({\n current\n });\n }\n\n render() {\n return (\n <Pagination current={this.state.current} onChange={this.handleChange} />\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
Set dropdown location using align
property in popupProps
prop.
import { Pagination } from '@alifd/next';\n\nconst handlePageSizeChange = size => console.log(size);\n\nconst containerStyle = {\n height: '300px',\n padding: 0,\n width: '100%',\n};\n\nconst boxStyle = {\n overflow: 'auto',\n position: 'relative',\n width: '100%',\n height: '200px',\n border: '1px solid black'\n};\n\nconst tempStyle = {\n height: '200px',\n display: 'flex',\n 'justify-content': 'center',\n 'align-items': 'center',\n};\n\nconst parentStyle = {\n display: 'flex',\n 'justify-content': 'space-between',\n};\n\nconst popupProps = {\n align: 'bl tl'\n};\n\nReactDOM.render(\n <div>\n <h3>default align - 'tl bl'</h3>\n <Pagination pageSizeSelector=\"dropdown\" total='10' pageSizePosition=\"start\" onPageSizeChange={handlePageSizeChange}/>\n <h3>custom align - 'bl tl'</h3>\n <Pagination pageSizeSelector=\"dropdown\" total='10' pageSizePosition=\"start\" onPageSizeChange={handlePageSizeChange} popupProps={popupProps}/>\n <h3>Inside parent with \"overlflow: auto\"</h3>\n <div style={containerStyle}>\n <div style={boxStyle}>\n <div style={tempStyle}>scroll down to see the example</div>\n <div style={parentStyle}>\n <div>\n <h3>default align - 'tl bl'</h3>\n <Pagination pageSizeSelector=\"dropdown\" total='10' pageSizePosition=\"start\" onPageSizeChange={handlePageSizeChange}/>\n </div>\n <div>\n <h3>custom align - 'bl tl'</h3>\n <Pagination pageSizeSelector=\"dropdown\" total='10' pageSizePosition=\"start\" onPageSizeChange={handlePageSizeChange} popupProps={popupProps}/>\n </div>\n </div>\n </div>\n </div>\n </div>,\n mountNode\n);\n\n
使用popupProps
prop中的align
属性设置下拉位置。
import { Pagination } from '@alifd/next';\n\nconst handlePageSizeChange = size => console.log(size);\n\nconst containerStyle = {\n height: '300px',\n padding: 0,\n width: '100%',\n};\n\nconst boxStyle = {\n overflow: 'auto',\n position: 'relative',\n width: '100%',\n height: '200px',\n border: '1px solid black'\n};\n\nconst tempStyle = {\n height: '200px',\n display: 'flex',\n 'justify-content': 'center',\n 'align-items': 'center',\n};\n\nconst parentStyle = {\n display: 'flex',\n 'justify-content': 'space-between',\n};\n\nconst popupProps = {\n align: 'bl tl'\n};\n\nReactDOM.render(\n <div>\n <h3>default align - 'tl bl'</h3>\n <Pagination pageSizeSelector=\"dropdown\" total='10' pageSizePosition=\"start\" onPageSizeChange={handlePageSizeChange}/>\n <h3>custom align - 'bl tl'</h3>\n <Pagination pageSizeSelector=\"dropdown\" total='10' pageSizePosition=\"start\" onPageSizeChange={handlePageSizeChange} popupProps={popupProps}/>\n <h3>Inside parent with \"overlflow: auto\"</h3>\n <div style={containerStyle}>\n <div style={boxStyle}>\n <div style={tempStyle}>scroll down to see the example</div>\n <div style={parentStyle}>\n <div>\n <h3>default align - 'tl bl'</h3>\n <Pagination pageSizeSelector=\"dropdown\" total='10' pageSizePosition=\"start\" onPageSizeChange={handlePageSizeChange}/>\n </div>\n <div>\n <h3>custom align - 'bl tl'</h3>\n <Pagination pageSizeSelector=\"dropdown\" total='10' pageSizePosition=\"start\" onPageSizeChange={handlePageSizeChange} popupProps={popupProps}/>\n </div>\n </div>\n </div>\n </div>\n </div>,\n mountNode\n);\n\n
You can set the page link's jump url by specifying the link
attribute. The value of the SEO, link attribute is a template string containing {page}
, and the Pagination component replaces the placeholder with a specific page number.
import { Pagination } from '@alifd/next';\n\nconst format = `${window.location.href}#/{page}`;\n\nReactDOM.render(\n <Pagination defaultCurrent={2} link={format} />,\n mountNode\n);
可以通过指定 link
属性来设置页码按钮的跳转链接,方便 SEO,link 属性的值为一个包含 {page}
的模板字符串,Pagination 组件会将该占位符替换为具体的页码数字。
import { Pagination } from '@alifd/next';\n\nconst format = `${window.location.href}#/{page}`;\n\nReactDOM.render(\n <Pagination defaultCurrent={2} link={format} />,\n mountNode\n);
The Page Size
property can be set to specify the number of records on the page.
\nThe pageSizeSelector
property can be set to specify whether to display the number of parts selected per page and the part shape.\nThe pageSizeList
property can specify the number of displayable values per page.
\nBy setting the pageSizePosition
property, you can specify whether the part selected by the display quantity per page is displayed at the beginning or end of the entire component .\nThe onPageSizeChange
property can be set to specify the callback function when the number of pages displayed changes.
import { Pagination } from '@alifd/next';\n\nconst handlePageSizeChange = size => console.log(size);\n\nReactDOM.render(\n <div>\n <h3>To hidden per page size selector</h3>\n <Pagination pageSizeSelector={false} />\n <h3>Type per page size selector of is dropdown,and as for the tail of the entire component</h3>\n <Pagination pageSizeSelector=\"dropdown\" pageSizePosition=\"end\" onPageSizeChange={handlePageSizeChange} />\n <h3>Filter type per page size selector, and use floating layout</h3>\n <Pagination pageSizeSelector=\"filter\" onPageSizeChange={handlePageSizeChange} useFloatLayout />\n </div>,\n mountNode\n);
可以通过设置 pageSize
属性来指定每页显示的数量。
\n可以通过设置 pageSizeSelector
属性来指定是否显示 每页数量选择 的部件以及部件形状。
\n可以通过设置 pageSizeList
属性来指定 每页显示数量 可选的值。
\n可以通过设置 pageSizePosition
属性来指定 每页显示数量选择 的部件显示在整个组件的开始位置还是结束位置。\n可以通过设置 onPageSizeChange
属性来指定每页显示的数量变化时的回调函数。
import { Pagination } from '@alifd/next';\n\nconst handlePageSizeChange = size => console.log(size);\n\nReactDOM.render(\n <div>\n <h3>To hidden per page size selector</h3>\n <Pagination pageSizeSelector={false} />\n <h3>Type per page size selector of is dropdown,and as for the tail of the entire component</h3>\n <Pagination pageSizeSelector=\"dropdown\" pageSizePosition=\"end\" onPageSizeChange={handlePageSizeChange} />\n <h3>Filter type per page size selector, and use floating layout</h3>\n <Pagination pageSizeSelector=\"filter\" onPageSizeChange={handlePageSizeChange} useFloatLayout />\n </div>,\n mountNode\n);
In a single-page application scenario, the Pagination component can use external jump methods to implement single-page internal jumps.
\n","order":"8"},"codes":{"jsx":"import { Pagination } from '@alifd/next';\nimport { hashHistory } from 'react-router';\n\nfunction handleChange(page) {\n hashHistory.push(page.toString());\n}\n\nReactDOM.render(\nimport { Pagination } from '@alifd/next';\nimport { hashHistory } from 'react-router';\n\nfunction handleChange(page) {\n hashHistory.push(page.toString());\n}\n\nReactDOM.render(\n <Pagination defaultCurrent={2} onChange={handleChange} />,\n mountNode\n);
单页应用场景下,Pagination 组件可以使用外部跳转的方法来实现单页内部跳转。
\n","order":"8"},"codes":{"jsx":"import { Pagination } from '@alifd/next';\nimport { hashHistory } from 'react-router';\n\nfunction handleChange(page) {\n hashHistory.push(page.toString());\n}\n\nReactDOM.render(\nimport { Pagination } from '@alifd/next';\nimport { hashHistory } from 'react-router';\n\nfunction handleChange(page) {\n hashHistory.push(page.toString());\n}\n\nReactDOM.render(\n <Pagination defaultCurrent={2} onChange={handleChange} />,\n mountNode\n);
You can set the forward and back arrow arrows to display by specifying the shape
property.
import { Pagination } from '@alifd/next';\n\nReactDOM.render(\n <div>\n <h3>normal</h3>\n <Pagination defaultCurrent={2} />\n <h3>arrow-only</h3>\n <Pagination defaultCurrent={2} shape=\"arrow-only\" />\n <h3>arrow-prev-only</h3>\n <Pagination defaultCurrent={2} shape=\"arrow-prev-only\" />\n <h3>no-border</h3>\n <Pagination defaultCurrent={2} shape=\"no-border\" type=\"simple\" />\n </div>,\n mountNode\n);
.next-pagination + .next-pagination {\n margin-top: 20px;\n}
可以通过指定 shape
属性来设置前进后退按钮箭头的显示方式。
import { Pagination } from '@alifd/next';\n\nReactDOM.render(\n <div>\n <h3>normal</h3>\n <Pagination defaultCurrent={2} />\n <h3>arrow-only</h3>\n <Pagination defaultCurrent={2} shape=\"arrow-only\" />\n <h3>arrow-prev-only</h3>\n <Pagination defaultCurrent={2} shape=\"arrow-prev-only\" />\n <h3>no-border</h3>\n <Pagination defaultCurrent={2} shape=\"no-border\" type=\"simple\" />\n </div>,\n mountNode\n);
.next-pagination + .next-pagination {\n margin-top: 20px;\n}
By default, the paging component does not display the total number. You can customize the total display result by using totalRender.
\n","order":"6"},"codes":{"jsx":"import { Pagination } from '@alifd/next';\n\nconst total = 50;\n\nReactDOM.render(\nimport { Pagination } from '@alifd/next';\n\nconst total = 50;\n\nReactDOM.render(\n <Pagination className=\"custom-pagination\" total={total} totalRender={total => `Total: ${total}`} />,\n mountNode\n);
.custom-pagination {\n display: inline-block;\n margin-left: 10px;\n}
分页组件默认不显示总数,你可以通过 totalRender 自定义总数的显示结果。
\n","order":"6"},"codes":{"jsx":"import { Pagination } from '@alifd/next';\n\nconst total = 50;\n\nReactDOM.render(\nimport { Pagination } from '@alifd/next';\n\nconst total = 50;\n\nReactDOM.render(\n <Pagination className=\"custom-pagination\" total={total} totalRender={total => `Total: ${total}`} />,\n mountNode\n);
.custom-pagination {\n display: inline-block;\n margin-left: 10px;\n}
You can set the paging size by specifying the size
property.
import { Pagination } from '@alifd/next';\n\nReactDOM.render(\n <div>\n <h3>small</h3>\n <Pagination defaultCurrent={2} size=\"small\" />\n <h3>medium</h3>\n <Pagination defaultCurrent={2} size=\"medium\" />\n <h3>large</h3>\n <Pagination defaultCurrent={2} size=\"large\" />\n </div>,\n mountNode\n);
可以通过指定 size
属性来设置分页的尺寸。
import { Pagination } from '@alifd/next';\n\nReactDOM.render(\n <div>\n <h3>small</h3>\n <Pagination defaultCurrent={2} size=\"small\" />\n <h3>medium</h3>\n <Pagination defaultCurrent={2} size=\"medium\" />\n <h3>large</h3>\n <Pagination defaultCurrent={2} size=\"large\" />\n </div>,\n mountNode\n);
Set the component type by specifying the type
property.
import { Pagination } from '@alifd/next';\n\nReactDOM.render(\n <div>\n <h3>normal</h3>\n <Pagination defaultCurrent={2} />\n <h3>simple</h3>\n <Pagination defaultCurrent={2} type=\"simple\" />\n <h3>mini</h3>\n <Pagination defaultCurrent={2} type=\"mini\" />\n </div>,\n mountNode\n);
可以通过指定 type
属性来设置分页的类型。
import { Pagination } from '@alifd/next';\n\nReactDOM.render(\n <div>\n <h3>normal</h3>\n <Pagination defaultCurrent={2} />\n <h3>simple</h3>\n <Pagination defaultCurrent={2} type=\"simple\" />\n <h3>mini</h3>\n <Pagination defaultCurrent={2} type=\"mini\" />\n </div>,\n mountNode\n);
import { Pagination } from '@alifd/next';\n\nconst change = function(value) {\n console.log(value);\n};\n\nReactDOM.render(\n <Pagination defaultCurrent={2} onChange={change} />,\n mountNode\n);
非受控分页,是指分页组件的状态由自己维护,组件值的改变可以通过 onChange
事件通知父组件,默认值由 defaultCurrent
初始化。
import { Pagination } from '@alifd/next';\n\nconst change = function(value) {\n console.log(value);\n};\n\nReactDOM.render(\n <Pagination defaultCurrent={2} onChange={change} />,\n mountNode\n);
When there is a lot of content to show when paged load processing is needed.
\nParam | \nDescripiton | \nType | \nDefault Value | \n
---|---|---|---|
size | \nSet the size of Pagination component option: 'small', 'medium', 'large' | \nEnum | \n'medium' | \n
type | \nSet the type of Pagination component option: 'normal', 'simple', 'mini' | \nEnum | \n'normal' | \n
shape | \nForward Back Button Style option: 'normal', 'arrow-only', 'arrow-prev-only', 'no-border' | \nEnum | \n'normal' | \n
current | \n(controlled)Current page number | \nNumber | \n- | \n
defaultCurrent | \n(uncontrolled)Initial page number | \nNumber | \n1 | \n
onChange | \nCallback function when page number changes signatures: Function(current: Number, e: Object) => void params: current: {Number} Changed number of pages _e_: {Object} Click envent object | \nFunction | \n() => {} | \n
total | \ntotal pages number | \nNumber | \n100 | \n
totalRender | \nThe rendering functions of total number signatures: Function(total: Number, range: Array) => void params: total: {Number} Total number range: {Array} The intervals of current data in the total number | \nFunction | \n- | \n
pageShowCount | \nThe number of pages displayed, more use '...' instead | \nNumber | \n5 | \n
pageSize | \nHow many records in a page | \nNumber | \n10 | \n
pageSizeSelector | \nSet to display selector type per page size option: false, 'filter', 'dropdown' | \nEnum | \nfalse | \n
pageSizeList | \nDisplay selector selectable records-number per page | \nArray<Number>/Array<Object> | \n[5, 10, 20] | \n
pageNumberRender | \nCustom page number rendering function, function for page number button and digital rendering of current page/total page count signatures: Function(index: Number) => ReactNode params: index: {Number} Page number of page, starting from 1 return: {ReactNode} Return rendering results | \nFunction | \nindex => index | \n
pageSizePosition | \nSet the position of pageSize selector option: 'start', 'end' | \nEnum | \n'start' | \n
useFloatLayout | \nIs there a floating layout when pageSize selector is displayed | \nBoolean | \nfalse | \n
onPageSizeChange | \nThe callback function trigget when the number of pageSize selector changes signatures: Function(pageSize: Number) => void params: pageSize: {Number} The number of pagesize changed | \nFunction | \n() => {} | \n
hideOnlyOnePage | \nWhether to hide the pager when the number of pages is 1 | \nBoolean | \nfalse | \n
showJump | \nWhen the number of pagination is 1, if the hidden pager type is set to normal, after the page number exceeds 5 pages, the jump input box and button will be displayed. When showJump is set to false, the jump zone is no longer displayed. | \nBoolean | \ntrue | \n
link | \nSet the jump link url of the page number button. Its value is a template string containing {page}, such as:http://www.taobao.com/{page} | \nString | \n- | \n
popupProps | \nProps for Popup | \nObject | \n- | \n
KeyBoard | \nDescripiton | \n
---|---|
Tab | \nswitch page | \n
Space | \nclick the button | \n
Enter | \nclick the button | \n
在有大量内容展现需要进行分页加载处理的时候。
\n参数 | \n说明 | \n类型 | \n默认值 | \n
---|---|---|---|
size | \n分页组件大小 可选值: 'small', 'medium', 'large' | \nEnum | \n'medium' | \n
type | \n分页组件类型 可选值: 'normal', 'simple', 'mini' | \nEnum | \n'normal' | \n
shape | \n前进后退按钮样式 可选值: 'normal', 'arrow-only', 'arrow-prev-only', 'no-border' | \nEnum | \n'normal' | \n
current | \n(受控)当前页码 | \nNumber | \n- | \n
defaultCurrent | \n(非受控)初始页码 | \nNumber | \n1 | \n
onChange | \n页码发生改变时的回调函数 签名: Function(current: Number, e: Object) => void 参数: current: {Number} 改变后的页码数 _e_: {Object} 点击事件对象 | \nFunction | \n() => {} | \n
total | \n总记录数 | \nNumber | \n100 | \n
totalRender | \n总数的渲染函数 签名: Function(total: Number, range: Array) => void 参数: total: {Number} 总数 range: {Array} 当前数据在总数中的区间 | \nFunction | \n- | \n
pageShowCount | \n页码显示的数量,更多的使用...代替 | \nNumber | \n5 | \n
pageSize | \n一页中的记录数 | \nNumber | \n10 | \n
pageSizeSelector | \n每页显示选择器类型 可选值: false, 'filter', 'dropdown' | \nEnum | \nfalse | \n
pageSizeList | \n每页显示选择器可选值 | \nArray<Number>/Array<Object> | \n[5, 10, 20] | \n
pageNumberRender | \n自定义页码渲染函数,函数作用于页码button以及当前页/总页数的数字渲染 签名: Function(index: Number) => ReactNode 参数: index: {Number} 分页的页码,从1开始 返回值: {ReactNode} 返回渲染结果 | \nFunction | \nindex => index | \n
pageSizePosition | \n每页显示选择器在组件中的位置 可选值: 'start', 'end' | \nEnum | \n'start' | \n
useFloatLayout | \n存在每页显示选择器时是否使用浮动布局 | \nBoolean | \nfalse | \n
onPageSizeChange | \n每页显示记录数量改变时的回调函数 签名: Function(pageSize: Number) => void 参数: pageSize: {Number} 改变后的每页显示记录数 | \nFunction | \n() => {} | \n
hideOnlyOnePage | \n当分页数为1时,是否隐藏分页器 | \nBoolean | \nfalse | \n
showJump | \ntype 设置为 normal 时,在页码数超过5页后,会显示跳转输入框与按钮,当设置 showJump 为 false 时,不再显示该跳转区域 | \nBoolean | \ntrue | \n
link | \n设置页码按钮的跳转链接,它的值为一个包含 {page} 的模版字符串,如:http://www.taobao.com/{page} | \nString | \n- | \n
popupProps | \n弹层组件属性,透传给Popup | \nObject | \n- | \n
按键 | \n说明 | \n
---|---|
Tab | \n切换页数 | \n
Space | \n按下按钮 | \n
Enter | \n按下按钮 | \n
simple usage
\n","order":"0"},"codes":{"jsx":"import { Paragraph } from '@alifd/next';\n\nconst content = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.';\n\nReactDOM.render(import { Paragraph } from '@alifd/next';\n\nconst content = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.';\n\nReactDOM.render(<div>\n <Paragraph>{content}</Paragraph>\n <br/>\n <Paragraph size=\"small\">{content}</Paragraph>\n</div>, mountNode);
最简单的用法。
\n","order":"0"},"codes":{"jsx":"import { Paragraph } from '@alifd/next';\n\nconst content = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.';\n\nReactDOM.render(import { Paragraph } from '@alifd/next';\n\nconst content = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.';\n\nReactDOM.render(<div>\n <Paragraph>{content}</Paragraph>\n <br/>\n <Paragraph size=\"small\">{content}</Paragraph>\n</div>, mountNode);
long for all text, short for those text within three lines
\n","order":"1"},"codes":{"jsx":"import { Paragraph } from '@alifd/next';\n\nconst content = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.';\n\nReactDOM.render(import { Paragraph } from '@alifd/next';\n\nconst content = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.';\n\nReactDOM.render(<div>\n <Paragraph>{content}</Paragraph>\n <br/>\n <Paragraph type=\"short\">{content}</Paragraph>\n</div>, mountNode);
用于短文本和长文本的区分,短文本的行间距会更小(一般为三行以内)
\n","order":"1"},"codes":{"jsx":"import { Paragraph } from '@alifd/next';\n\nconst content = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.';\n\nReactDOM.render(import { Paragraph } from '@alifd/next';\n\nconst content = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.';\n\nReactDOM.render(<div>\n <Paragraph>{content}</Paragraph>\n <br/>\n <Paragraph type=\"short\">{content}</Paragraph>\n</div>, mountNode);
Paragraphs are used to control the overall text visual of the page, and are mainly represented by the line spacing and text size.
\nParam | \nDescripiton | \nType | \nDefault Value | \n
---|---|---|---|
size | \ncomponent size. Default: medium medium, small small | \nString | \n'medium' | \n
type | \nWhat way to show paragraphs. Default: long shows all text, short shows three lines (not mandatory) | \nString | \n'long' | \n
(已废弃,请使用Typography)段落用于控制页面整体的文本视觉,主要由行间距及文本大小体现。
\n参数 | \n说明 | \n类型 | \n默认值 | \n
---|---|---|---|
size | \n组件大小。 可选值: 'medium'(中号) 'small'(小号) | \nEnum | \n'medium' | \n
type | \n什么方式展示段落 可选值: 'long'(展示所有文本) 'short'(展示三行以内(非强制)) | \nEnum | \n'long' | \n
A basic progress bar, using percent
to control current progress, and control the tail text with textRender
.
import { Progress } from '@alifd/next';\n\nReactDOM.render(<div>\n <Progress percent={30} textRender={() => ''} />\n <Progress percent={50} />\n <Progress percent={90} />\n <Progress percent={40} />\n <Progress percent={40} hasBorder size=\"large\" />\n</div>, mountNode);
普通模式的进度条,通过 percent
属性指定进度,通过 textRender
控制右侧文本信息的展示,\n通过 hasBorder
属性设置组件是否包含边框。
import { Progress } from '@alifd/next';\n\nReactDOM.render(<div>\n <Progress percent={30} textRender={() => ''} />\n <Progress percent={50} />\n <Progress percent={90} />\n <Progress percent={40} />\n <Progress percent={40} hasBorder size=\"large\" />\n</div>, mountNode);
A simple progress circle.
\n","order":"1"},"codes":{"jsx":"import { Progress, Icon } from '@alifd/next';\n\nReactDOM.render(import { Progress, Icon } from '@alifd/next';\n\nReactDOM.render(<div>\n <Progress percent={30} shape=\"circle\" /> \n <Progress percent={50} shape=\"circle\" /> \n <Progress percent={80} shape=\"circle\" textRender={() => ''}/> \n <Progress percent={100} shape=\"circle\" textRender={() => <Icon type=\"select\" size=\"xl\" />} />\n</div>, mountNode);
通过 shape
属性可以改变进度指示器的外观,当取值为 circle
时为圆形进度条。
import { Progress, Icon } from '@alifd/next';\n\nReactDOM.render(<div>\n <Progress percent={30} shape=\"circle\" /> \n <Progress percent={50} shape=\"circle\" /> \n <Progress percent={80} shape=\"circle\" textRender={() => ''}/> \n <Progress percent={100} shape=\"circle\" textRender={() => <Icon type=\"select\" size=\"xl\" />} />\n</div>, mountNode);
Use color
prop to controll progress bar color. The Progress Component has three APIs which can controll the color of progress bar and it's priority: color > progressive > state.
import { Progress, Icon } from '@alifd/next';\n\nReactDOM.render(<div>\n <Progress percent={30} shape=\"circle\" color=\"#AF5F3C\"/> \n <Progress percent={40} shape=\"circle\"/> \n <Progress percent={50} shape=\"circle\" color=\"#E91E63\" backgroundColor={'#00BCD4'} /> \n <Progress percent={90} shape=\"circle\" color=\"rgba(119,66,141, 0.9)\" textRender={() => <Icon type=\"select\" size=\"xl\" />} />\n <br /><br />\n <Progress percent={30} shape=\"line\" color=\"rgb(208,16,76)\"/>\n <Progress percent={40} shape=\"line\"/>\n <Progress percent={50} shape=\"line\" color=\"#E91E63\" backgroundColor={'#00BCD4'} />\n <Progress percent={90} shape=\"line\" color=\"blue\" textRender={() => <Icon type=\"select\" size=\"medium\" />} />\n</div>, mountNode);
通过 color
属性可以改变进度条的颜色。Progress 有三个API可以改变进度条的颜色,其优先级为 color > progressive > state。
import { Progress, Icon } from '@alifd/next';\n\nReactDOM.render(<div>\n <Progress percent={30} shape=\"circle\" color=\"#AF5F3C\"/> \n <Progress percent={40} shape=\"circle\"/> \n <Progress percent={50} shape=\"circle\" color=\"#E91E63\" backgroundColor={'#00BCD4'} /> \n <Progress percent={90} shape=\"circle\" color=\"rgba(119,66,141, 0.9)\" textRender={() => <Icon type=\"select\" size=\"xl\" />} />\n <br /><br />\n <Progress percent={30} shape=\"line\" color=\"rgb(208,16,76)\"/>\n <Progress percent={40} shape=\"line\"/>\n <Progress percent={50} shape=\"line\" color=\"#E91E63\" backgroundColor={'#00BCD4'} />\n <Progress percent={90} shape=\"line\" color=\"blue\" textRender={() => <Icon type=\"select\" size=\"medium\" />} />\n</div>, mountNode);
The dynmaic exmaple. Attention: Animation require time to finish, so changing percent too frequently may cause display delay.
\n","order":"6"},"codes":{"jsx":"import { Progress, Button, Icon } from '@alifd/next';\n\n\nclass CustomProgress extends React.Component {\n constructor(props) {\n super(props);\n this.state = {\n percent: 0\n };\n }\n\n addProgress = () => {\n this.setState(prevState => {\n return {\n percent: prevState.percent + 10\n };\n });\n }\n\n minusProgress = () => {\n this.setState(prevState => {\n return {\n percent: prevState.percent - 10\n };\n });\n }\n\n render() {\n const state = this.state;\n return (import { Progress, Button, Icon } from '@alifd/next';\n\n\nclass CustomProgress extends React.Component {\n constructor(props) {\n super(props);\n this.state = {\n percent: 0\n };\n }\n\n addProgress = () => {\n this.setState(prevState => {\n return {\n percent: prevState.percent + 10\n };\n });\n }\n\n minusProgress = () => {\n this.setState(prevState => {\n return {\n percent: prevState.percent - 10\n };\n });\n }\n\n render() {\n const state = this.state;\n return (<div>\n <div className=\"progress-panel\">\n <Button.Group>\n <Button onClick={this.minusProgress} disabled={state.percent === 0}><Icon type=\"minus\" /></Button>\n <Button onClick={this.addProgress} disabled={state.percent === 100}><Icon type=\"add\" /></Button>\n </Button.Group>\n </div>\n\n <Progress percent={state.percent} progressive size=\"large\" />\n <br /><br />\n <Progress percent={state.percent} progressive shape=\"circle\" size=\"large\" />\n </div>);\n }\n}\n\nReactDOM.render(<CustomProgress />, mountNode);
.progress-panel {\n display: flex;\n margin-bottom: 14px;\n}\n\n.custom-select {\n margin-right: 20px;\n}
此时为增强模式的进度条,会根据当前进度展示不同的样式。注: css animation完成需要时间, 数据调整过于频繁会导致显示延迟。
\n","order":"6"},"codes":{"jsx":"import { Progress, Button, Icon } from '@alifd/next';\n\n\nclass CustomProgress extends React.Component {\n constructor(props) {\n super(props);\n this.state = {\n percent: 0\n };\n }\n\n addProgress = () => {\n this.setState(prevState => {\n return {\n percent: prevState.percent + 10\n };\n });\n }\n\n minusProgress = () => {\n this.setState(prevState => {\n return {\n percent: prevState.percent - 10\n };\n });\n }\n\n render() {\n const state = this.state;\n return (import { Progress, Button, Icon } from '@alifd/next';\n\n\nclass CustomProgress extends React.Component {\n constructor(props) {\n super(props);\n this.state = {\n percent: 0\n };\n }\n\n addProgress = () => {\n this.setState(prevState => {\n return {\n percent: prevState.percent + 10\n };\n });\n }\n\n minusProgress = () => {\n this.setState(prevState => {\n return {\n percent: prevState.percent - 10\n };\n });\n }\n\n render() {\n const state = this.state;\n return (<div>\n <div className=\"progress-panel\">\n <Button.Group>\n <Button onClick={this.minusProgress} disabled={state.percent === 0}><Icon type=\"minus\" /></Button>\n <Button onClick={this.addProgress} disabled={state.percent === 100}><Icon type=\"add\" /></Button>\n </Button.Group>\n </div>\n\n <Progress percent={state.percent} progressive size=\"large\" />\n <br /><br />\n <Progress percent={state.percent} progressive shape=\"circle\" size=\"large\" />\n </div>);\n }\n}\n\nReactDOM.render(<CustomProgress />, mountNode);
.progress-panel {\n display: flex;\n margin-bottom: 14px;\n}\n\n.custom-select {\n margin-right: 20px;\n}
we can define how Percentage text to display by using textRender
.\nThe exapme below will show a progressbar with accuracy of 2 decimal places and done icon when reached 100%.
import { Progress, Icon } from '@alifd/next';\n\nconst textRender = percent => {\n if (percent === 100) {\n return <Icon type=\"select\" size=\"medium\" />;\n }\n return `${percent.toFixed(2)}%`;\n};\n\nReactDOM.render(<div>\n {[1, 2, 3, 4, 5, 6].map((value, index) => <Progress key={index} percent={value / 6 * 100} shape=\"circle\" color={`hsl(${index * 60 + 60}, 90%, 50%)`} textRender={textRender}/>)}\n {[1, 2, 3, 4, 5, 6].map((value, index) => <Progress key={index} percent={value / 6 * 100} shape=\"line\" color={`hsl(${index * 60 + 60}, 90%, 50%)`} textRender={textRender}/>)}\n</div>, mountNode);
textRender
控制百分比信息的展示,通过自定义textRender
个性化百分比渲染. 下面给一个 百分比进度取2位,当达到100%是显示Icon的progressbar.
import { Progress, Icon } from '@alifd/next';\n\nconst textRender = percent => {\n if (percent === 100) {\n return <Icon type=\"select\" size=\"medium\" />;\n }\n return `${percent.toFixed(2)}%`;\n};\n\nReactDOM.render(<div>\n {[1, 2, 3, 4, 5, 6].map((value, index) => <Progress key={index} percent={value / 6 * 100} shape=\"circle\" color={`hsl(${index * 60 + 60}, 90%, 50%)`} textRender={textRender}/>)}\n {[1, 2, 3, 4, 5, 6].map((value, index) => <Progress key={index} percent={value / 6 * 100} shape=\"line\" color={`hsl(${index * 60 + 60}, 90%, 50%)`} textRender={textRender}/>)}\n</div>, mountNode);
Progressive progresses.
\n","order":"4"},"codes":{"jsx":"import { Progress } from '@alifd/next';\n\nReactDOM.render(import { Progress } from '@alifd/next';\n\nReactDOM.render(<div>\n <Progress percent={20} progressive />\n <Progress percent={60} progressive />\n <Progress percent={90} progressive />\n</div>, mountNode);
当开启 progressive
模式时,Progress 组件会根据自身的进度自动设置展现的颜色值。\n注意,此时会忽略用户设置的 state
的属性值。
import { Progress } from '@alifd/next';\n\nReactDOM.render(<div>\n <Progress percent={20} progressive />\n <Progress percent={60} progressive />\n <Progress percent={90} progressive />\n</div>, mountNode);
Change the size of progress.
\n","order":"2"},"codes":{"jsx":"import { Progress } from '@alifd/next';\n\nReactDOM.render(import { Progress } from '@alifd/next';\n\nReactDOM.render(<div>\n <Progress percent={30} size=\"small\" />\n <Progress percent={50} size=\"medium\" />\n <Progress percent={90} size=\"large\" />\n <br />\n <Progress percent={30} size=\"small\" shape=\"circle\" /> \n <Progress percent={50} size=\"medium\" shape=\"circle\" /> \n <Progress percent={90} size=\"large\" shape=\"circle\" />\n</div>, mountNode);
可以通过 size
属性制定进度条的大小。
import { Progress } from '@alifd/next';\n\nReactDOM.render(<div>\n <Progress percent={30} size=\"small\" />\n <Progress percent={50} size=\"medium\" />\n <Progress percent={90} size=\"large\" />\n <br />\n <Progress percent={30} size=\"small\" shape=\"circle\" /> \n <Progress percent={50} size=\"medium\" shape=\"circle\" /> \n <Progress percent={90} size=\"large\" shape=\"circle\" />\n</div>, mountNode);
Change the state of Progress by state
, supporting normal
, success
, error
.
import { Progress } from '@alifd/next';\n\nReactDOM.render(<div className=\"\">\n <Progress percent={20} shape=\"circle\" state=\"normal\" className=\"custom-progress\" />\n <Progress percent={95} shape=\"circle\" state=\"success\" className=\"custom-progress\" />\n <Progress percent={95} shape=\"circle\" state=\"error\" className=\"custom-progress\" />\n</div>, mountNode);
.custom-progress {\n margin: 0 20px;\n}
用户可以通过 state
属性自定义当前进度的展现状态,可取值为 normal
, success
, error
分别表示普通、成功、失败这三种状态。
import { Progress } from '@alifd/next';\n\nReactDOM.render(<div className=\"\">\n <Progress percent={20} shape=\"circle\" state=\"normal\" className=\"custom-progress\" />\n <Progress percent={95} shape=\"circle\" state=\"success\" className=\"custom-progress\" />\n <Progress percent={95} shape=\"circle\" state=\"error\" className=\"custom-progress\" />\n</div>, mountNode);
.custom-progress {\n margin: 0 20px;\n}
Progress used to show the progress of a task.
\nIf a task will take long time to complete, it could be use a Progress
to show the progress. Such as:
Param | \nDescripiton | \nType | \nDefault Value | \n
---|---|---|---|
size | \nSize option: 'small', 'medium', 'large' | \nEnum | \n'medium' | \n
shape | \nShape option: 'circle', 'line' | \nEnum | \n'line' | \n
percent | \nCurrent percente of progress | \nNumber | \n0 | \n
state | \nState of progress, priority: color > progressive > state option: 'normal', 'success', 'error' | \nEnum | \n'normal' | \n
progressive | \nProgressive mode (with dynamic color), priority: color > progressive > state | \nBoolean | \nfalse | \n
hasBorder | \nHas border for progress line | \nBoolean | \nfalse | \n
textRender | \nText render signature: Function(percent: Number) => ReactNode parameter: percent: {Number} current percent return: {ReactNode} text node | \nFunction | \npercent => ${Math.floor(percent)}% | \n
color | \nprogressbar color, priority: color > progressive > state | \nString | \n'' | \n
展示操作的当前进度。
\n在操作需要较长时间才能完成时,为用户显示该操作的当前进度和状态。
\n参数 | \n说明 | \n类型 | \n默认值 | \n
---|---|---|---|
size | \n尺寸 可选值: 'small', 'medium', 'large' | \nEnum | \n'medium' | \n
shape | \n形态 可选值: 'circle', 'line' | \nEnum | \n'line' | \n
percent | \n所占百分比 | \nNumber | \n0 | \n
state | \n进度状态, 显示优先级: color > progressive > state 可选值: 'normal', 'success', 'error' | \nEnum | \n'normal' | \n
progressive | \n是否为色彩阶段变化模式, 显示优先级: color > progressive > state | \nBoolean | \nfalse | \n
hasBorder | \n是否添加 Border(只适用于 Line Progress) | \nBoolean | \nfalse | \n
textRender | \n文本渲染函数 签名: Function(percent: Number, option: Object) => ReactNode 参数: percent: {Number} 当前的进度信息 option: {Object} 额外的参数 返回值: {ReactNode} 返回文本节点 | \nFunction | \npercent => ${Math.floor(percent)}% | \n
color | \n进度条颜色, 显示优先级: color > progressive > state | \nString | \n- | \n
backgroundColor | \n背景色 | \nString | \n- | \n
Please refer to ARIA and KeyBoard
.
import { Radio } from '@alifd/next';\n\nconst RadioGroup = Radio.Group;\nReactDOM.render(\n <div>\n <span id=\"radio-a11y\">Programming language :</span>\n <RadioGroup aria-labelledby=\"radio-a11y\">\n <Radio id=\"python\" value=\"python\">python</Radio>\n <Radio id=\"java\" value=\"java\">java</Radio>\n <Radio id=\"c\" value=\"c\">c</Radio>\n </RadioGroup>\n </div>\n , mountNode);\n
请参考ARIA and KeyBoard
。
import { Radio } from '@alifd/next';\n\nconst RadioGroup = Radio.Group;\nReactDOM.render(\n <div>\n <span id=\"radio-a11y\">Programming language :</span>\n <RadioGroup aria-labelledby=\"radio-a11y\">\n <Radio id=\"python\" value=\"python\">python</Radio>\n <Radio id=\"java\" value=\"java\">java</Radio>\n <Radio id=\"c\" value=\"c\">c</Radio>\n </RadioGroup>\n </div>\n , mountNode);\n
import { Radio } from '@alifd/next';\n\nReactDOM.render((\n <div>\n <h4>Without Label</h4>\n <Radio defaultChecked /> \n <Radio checked /> \n <Radio disabled /> \n <Radio checked disabled /> \n <Radio />\n <br />\n <h4>With Label</h4>\n <Radio id=\"apple\">Apple</Radio> \n <Radio id=\"banana\" /><label htmlFor=\"banana\" className=\"next-radio-label\">Banana</label> \n <Radio id=\"apple2\" label=\"Apple\" className=\"testClassname\" />\n </div>\n), mountNode);
使用 Radio
渲染的基本组件。
import { Radio } from '@alifd/next';\n\nReactDOM.render((\n <div>\n <h4>Without Label</h4>\n <Radio defaultChecked /> \n <Radio checked /> \n <Radio disabled /> \n <Radio checked disabled /> \n <Radio />\n <br />\n <h4>With Label</h4>\n <Radio id=\"apple\">Apple</Radio> \n <Radio id=\"banana\" /><label htmlFor=\"banana\" className=\"next-radio-label\">Banana</label> \n <Radio id=\"apple2\" label=\"Apple\" className=\"testClassname\" />\n </div>\n), mountNode);
import { Radio } from '@alifd/next';\n\nconst RadioGroup = Radio.Group;\n\nconst list = [\n {\n value: 'apple',\n label: 'Apple',\n disabled: false\n }, {\n value: 'pear',\n label: 'Pear'\n }, {\n value: 'orange',\n label: 'Orange',\n disabled: true\n }\n];\n\nclass ControlApp extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n value1: 'apple',\n value2: 'apple',\n value3: ''\n };\n\n this.onNestChange = this.onNestChange.bind(this);\n this.onSmallChange = this.onSmallChange.bind(this);\n this.onMediumChange = this.onMediumChange.bind(this);\n }\n\n onSmallChange(value) {\n this.setState({\n value1: value\n });\n }\n\n onMediumChange(value) {\n this.setState({\n value2: value\n });\n }\n\n onNestChange(value) {\n this.setState({\n value3: value\n });\n }\n\n render() {\n return (\n <div>\n <h4>Small size</h4>\n <RadioGroup dataSource={list} shape=\"button\" size=\"small\" value={this.state.value1} onChange={this.onSmallChange} />\n <br/>\n <br/>\n <h4>Medium size (default)</h4>\n <RadioGroup dataSource={list} shape=\"button\" size=\"medium\" value={this.state.value2} onChange={this.onMediumChange} />\n <br/>\n <br/>\n <h4>Large size</h4>\n <RadioGroup shape=\"button\" size=\"large\" value={this.state.value3} onChange={this.onNestChange}>\n <Radio id=\"banana\" value=\"banana\">Banana</Radio>\n <Radio id=\"watermelon\" value=\"watermelon\">Watermelon</Radio>\n <Radio id=\"peach\" value=\"peach\">Peach</Radio>\n </RadioGroup>\n <br/>\n <br/>\n <h4>Disabled and Selected-Disabled status</h4>\n <RadioGroup shape=\"button\" value=\"banana\" onChange={this.onNestChange}>\n <Radio id=\"peach\" disabled value=\"peach\">Peach</Radio>\n <Radio id=\"banana\" disabled value=\"banana\">Banana</Radio>\n </RadioGroup>\n\n </div>\n );\n }\n}\n\nReactDOM.render(<ControlApp />, mountNode);
使用 RadioGroup
渲染的组,通过设置 shape="button"
可以让组件以按钮形式展示,同时可以通过 size
来控制组件大小。
import { Radio } from '@alifd/next';\n\nconst RadioGroup = Radio.Group;\n\nconst list = [\n {\n value: 'apple',\n label: 'Apple',\n disabled: false\n }, {\n value: 'pear',\n label: 'Pear'\n }, {\n value: 'orange',\n label: 'Orange',\n disabled: true\n }\n];\n\nclass ControlApp extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n value1: 'apple',\n value2: 'apple',\n value3: ''\n };\n\n this.onNestChange = this.onNestChange.bind(this);\n this.onSmallChange = this.onSmallChange.bind(this);\n this.onMediumChange = this.onMediumChange.bind(this);\n }\n\n onSmallChange(value) {\n this.setState({\n value1: value\n });\n }\n\n onMediumChange(value) {\n this.setState({\n value2: value\n });\n }\n\n onNestChange(value) {\n this.setState({\n value3: value\n });\n }\n\n render() {\n return (\n <div>\n <h4>Small size</h4>\n <RadioGroup dataSource={list} shape=\"button\" size=\"small\" value={this.state.value1} onChange={this.onSmallChange} />\n <br/>\n <br/>\n <h4>Medium size (default)</h4>\n <RadioGroup dataSource={list} shape=\"button\" size=\"medium\" value={this.state.value2} onChange={this.onMediumChange} />\n <br/>\n <br/>\n <h4>Large size</h4>\n <RadioGroup shape=\"button\" size=\"large\" value={this.state.value3} onChange={this.onNestChange}>\n <Radio id=\"banana\" value=\"banana\">Banana</Radio>\n <Radio id=\"watermelon\" value=\"watermelon\">Watermelon</Radio>\n <Radio id=\"peach\" value=\"peach\">Peach</Radio>\n </RadioGroup>\n <br/>\n <br/>\n <h4>Disabled and Selected-Disabled status</h4>\n <RadioGroup shape=\"button\" value=\"banana\" onChange={this.onNestChange}>\n <Radio id=\"peach\" disabled value=\"peach\">Peach</Radio>\n <Radio id=\"banana\" disabled value=\"banana\">Banana</Radio>\n </RadioGroup>\n\n </div>\n );\n }\n}\n\nReactDOM.render(<ControlApp />, mountNode);
import { Radio } from '@alifd/next';\n\nconst RadioGroup = Radio.Group;\n\nconst list = [\n {\n value: 'appale',\n label: 'Appale'\n }, {\n value: 'pear',\n label: 'Pear'\n }, {\n value: 'orange',\n label: 'Orange'\n }\n];\n\nclass ControlApp extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n value: 'orange'\n };\n\n this.onChange = this.onChange.bind(this);\n }\n\n onChange(value) {\n this.setState({\n value: value\n });\n console.log('onChange', value);\n }\n\n onClick(e) {\n console.log('onClick', e);\n }\n\n render() {\n return (\n <div>\n normal: <RadioGroup dataSource={list} value={this.state.value} onChange={this.onChange} />\n <br />\n <br />\n <br />\n disabled: <RadioGroup disabled dataSource={list} value={this.state.value} onChange={this.onChange} />\n </div>\n );\n }\n}\n\nReactDOM.render(<ControlApp />, mountNode);
使用 RadioGroup
渲染的组,通过设置 value
属性可以让组件变成受限组件。
import { Radio } from '@alifd/next';\n\nconst RadioGroup = Radio.Group;\n\nconst list = [\n {\n value: 'appale',\n label: 'Appale'\n }, {\n value: 'pear',\n label: 'Pear'\n }, {\n value: 'orange',\n label: 'Orange'\n }\n];\n\nclass ControlApp extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n value: 'orange'\n };\n\n this.onChange = this.onChange.bind(this);\n }\n\n onChange(value) {\n this.setState({\n value: value\n });\n console.log('onChange', value);\n }\n\n onClick(e) {\n console.log('onClick', e);\n }\n\n render() {\n return (\n <div>\n normal: <RadioGroup dataSource={list} value={this.state.value} onChange={this.onChange} />\n <br />\n <br />\n <br />\n disabled: <RadioGroup disabled dataSource={list} value={this.state.value} onChange={this.onChange} />\n </div>\n );\n }\n}\n\nReactDOM.render(<ControlApp />, mountNode);
Grouping <Radio>
with <Radio.Group>
.
\n
\n
\n
\n
import { Radio } from '@alifd/next';\n\nconst Shape = {\n NORMAL: 'normal',\n BUTTON: 'button'\n};\n\nconst ItemDirection = {\n HORIZON: 'hoz',\n VERTICAL: 'ver'\n};\n\nclass RadioGroup extends React.Component {\n state = {\n shape: Shape.NORMAL,\n itemDirection: ItemDirection.HORIZON\n }\n\n onShapeChange = (shape) => {\n this.setState({ shape });\n }\n\n onItemDirectionChange = (itemDirection) => {\n this.setState({ itemDirection });\n }\n\n render() {\n return (\n <div>\n <h5>Choose a shape</h5>\n <p>\n <Radio.Group\n shape=\"button\"\n value={this.state.shape}\n onChange={this.onShapeChange}\n >\n <Radio value={Shape.NORMAL}>Normal</Radio>\n <Radio value={Shape.BUTTON}>Button</Radio>\n </Radio.Group>\n </p>\n <h5>Choose an align-type of the item</h5>\n <p>\n <Radio.Group\n shape=\"button\"\n value={this.state.itemDirection}\n onChange={this.onItemDirectionChange}\n >\n <Radio value={ItemDirection.HORIZON}>Horizon</Radio>\n <Radio\n value={ItemDirection.VERTICAL}\n disabled={this.state.shape === Shape.BUTTON}\n >Vertical</Radio>\n </Radio.Group>\n </p>\n <div className=\"rendered-container\">\n <h3>Rendered Result</h3>\n <Radio.Group\n shape={this.state.shape}\n itemDirection={this.state.itemDirection}\n >\n <Radio value=\"react\">React</Radio>\n <Radio value=\"vue\">Vue</Radio>\n <Radio value=\"angular\">Angular</Radio>\n </Radio.Group>\n </div>\n </div>\n );\n }\n}\n\nReactDOM.render(<RadioGroup />, mountNode);
.rendered-container {\n margin: 32px 0 0;\n padding: 0 24px 24px;\n border: 3px dashed #aaa;\n border-radius: 11px;\n}
使用 <Radio.Group>
渲染 <Radio>
分组。
\n
\n
\n
\n
import { Radio } from '@alifd/next';\n\nconst Shape = {\n NORMAL: 'normal',\n BUTTON: 'button'\n};\n\nconst ItemDirection = {\n HORIZON: 'hoz',\n VERTICAL: 'ver'\n};\n\nclass RadioGroup extends React.Component {\n state = {\n shape: Shape.NORMAL,\n itemDirection: ItemDirection.HORIZON\n }\n\n onShapeChange = (shape) => {\n this.setState({ shape });\n }\n\n onItemDirectionChange = (itemDirection) => {\n this.setState({ itemDirection });\n }\n\n render() {\n return (\n <div>\n <h5>Choose a shape</h5>\n <p>\n <Radio.Group\n shape=\"button\"\n value={this.state.shape}\n onChange={this.onShapeChange}\n >\n <Radio value={Shape.NORMAL}>Normal</Radio>\n <Radio value={Shape.BUTTON}>Button</Radio>\n </Radio.Group>\n </p>\n <h5>Choose an align-type of the item</h5>\n <p>\n <Radio.Group\n shape=\"button\"\n value={this.state.itemDirection}\n onChange={this.onItemDirectionChange}\n >\n <Radio value={ItemDirection.HORIZON}>Horizon</Radio>\n <Radio\n value={ItemDirection.VERTICAL}\n disabled={this.state.shape === Shape.BUTTON}\n >Vertical</Radio>\n </Radio.Group>\n </p>\n <div className=\"rendered-container\">\n <h3>Rendered Result</h3>\n <Radio.Group\n shape={this.state.shape}\n itemDirection={this.state.itemDirection}\n >\n <Radio value=\"react\">React</Radio>\n <Radio value=\"vue\">Vue</Radio>\n <Radio value=\"angular\">Angular</Radio>\n </Radio.Group>\n </div>\n </div>\n );\n }\n}\n\nReactDOM.render(<RadioGroup />, mountNode);
.rendered-container {\n margin: 32px 0 0;\n padding: 0 24px 24px;\n border: 3px dashed #aaa;\n border-radius: 11px;\n}
import { Radio } from '@alifd/next';\n\nconst RadioGroup = Radio.Group;\n\nclass NestApp extends React.Component {\n\n constructor(props) {\n super(props);\n\n this.state = {\n value: 'orange'\n };\n\n this.onChange = this.onChange.bind(this);\n }\n\n onChange(value) {\n this.setState({\n value: value\n });\n }\n\n render() {\n return (\n <div>\n <label id=\"groupId\">Choose fruit</label><br/>\n <RadioGroup value={this.state.value} onChange={this.onChange} aria-labelledby=\"groupId\">\n <Radio id=\"apple\" value=\"apple\">Apple</Radio>\n <Radio id=\"watermelon\" value=\"watermelon\">Watermelon</Radio>\n <Radio id=\"orange\" value=\"orange\">Orange</Radio>\n </RadioGroup>\n </div>\n );\n }\n}\n\nReactDOM.render(<NestApp />, mountNode);
使用 RadioGroup
,通过直接嵌套 Radio
组件来渲染的组。
import { Radio } from '@alifd/next';\n\nconst RadioGroup = Radio.Group;\n\nclass NestApp extends React.Component {\n\n constructor(props) {\n super(props);\n\n this.state = {\n value: 'orange'\n };\n\n this.onChange = this.onChange.bind(this);\n }\n\n onChange(value) {\n this.setState({\n value: value\n });\n }\n\n render() {\n return (\n <div>\n <label id=\"groupId\">Choose fruit</label><br/>\n <RadioGroup value={this.state.value} onChange={this.onChange} aria-labelledby=\"groupId\">\n <Radio id=\"apple\" value=\"apple\">Apple</Radio>\n <Radio id=\"watermelon\" value=\"watermelon\">Watermelon</Radio>\n <Radio id=\"orange\" value=\"orange\">Orange</Radio>\n </RadioGroup>\n </div>\n );\n }\n}\n\nReactDOM.render(<NestApp />, mountNode);
import { Radio } from '@alifd/next';\n\nconst RadioGroup = Radio.Group;\n\nconst list = [\n {\n value: 'apple',\n label: 'Apple',\n disabled: false\n }, {\n value: 'pear',\n label: 'Pear',\n disabled: true\n }, {\n value: 'orange',\n label: 'Orange'\n }\n];\n\nconst UnControlApp = () => {\n return (\n <div>\n <RadioGroup dataSource={list} defaultValue={'apple'} />\n </div>\n );\n};\n\nReactDOM.render(<UnControlApp />, mountNode);
使用 RadioGroup
渲染的组,通过设置 defaultValue
属性可以让组件变成非受限组件。
import { Radio } from '@alifd/next';\n\nconst RadioGroup = Radio.Group;\n\nconst list = [\n {\n value: 'apple',\n label: 'Apple',\n disabled: false\n }, {\n value: 'pear',\n label: 'Pear',\n disabled: true\n }, {\n value: 'orange',\n label: 'Orange'\n }\n];\n\nconst UnControlApp = () => {\n return (\n <div>\n <RadioGroup dataSource={list} defaultValue={'apple'} />\n </div>\n );\n};\n\nReactDOM.render(<UnControlApp />, mountNode);
import { Radio, Grid } from '@alifd/next';\n\nconst { Row, Col } = Grid;\nconst RadioGroup = Radio.Group;\n\nclass ControlApp extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n value: 'orange',\n other: 0\n };\n\n this.onChange = this.onChange.bind(this);\n }\n\n onChange(value) {\n this.setState({\n value: value\n });\n console.log('onChange', value);\n }\n\n onClick(e) {\n console.log('onClick', e);\n }\n\n render() {\n return (\n <div >\n <h4>Grid Layout</h4>\n <RadioGroup onChange={this.onChange} style={{ width: '1000px'}} >\n <Row>\n <Col span=\"8\">\n <Radio value=\"apple1\" onClick={this.onClick} >Apple</Radio>\n </Col>\n <Col span=\"8\">\n <Radio value=\"pear1\" onClick={this.onClick} >Pear</Radio>\n </Col>\n <Col span=\"8\">\n <Radio value=\"banana1\" onClick={this.onClick} >Banana</Radio>\n </Col>\n </Row>\n <Row>\n <Col span=\"8\">\n <Radio value=\"peach\" onClick={this.onClick} >Peach</Radio>\n </Col>\n <Col span=\"8\">\n <Radio value=\"watermelon\" onClick={this.onClick} >Watermelon</Radio>\n </Col>\n <Col span=\"8\">\n <Radio value=\"strawberry\" onClick={this.onClick} >Strawberry</Radio>\n </Col>\n </Row>\n <Row>Just simple context</Row>\n </RadioGroup>\n </div>\n );\n }\n}\n\nReactDOM.render(<ControlApp />, mountNode);
使用 Grid
布局 RadioGroup
中的选项。
import { Radio, Grid } from '@alifd/next';\n\nconst { Row, Col } = Grid;\nconst RadioGroup = Radio.Group;\n\nclass ControlApp extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n value: 'orange',\n other: 0\n };\n\n this.onChange = this.onChange.bind(this);\n }\n\n onChange(value) {\n this.setState({\n value: value\n });\n console.log('onChange', value);\n }\n\n onClick(e) {\n console.log('onClick', e);\n }\n\n render() {\n return (\n <div >\n <h4>Grid Layout</h4>\n <RadioGroup onChange={this.onChange} style={{ width: '1000px'}} >\n <Row>\n <Col span=\"8\">\n <Radio value=\"apple1\" onClick={this.onClick} >Apple</Radio>\n </Col>\n <Col span=\"8\">\n <Radio value=\"pear1\" onClick={this.onClick} >Pear</Radio>\n </Col>\n <Col span=\"8\">\n <Radio value=\"banana1\" onClick={this.onClick} >Banana</Radio>\n </Col>\n </Row>\n <Row>\n <Col span=\"8\">\n <Radio value=\"peach\" onClick={this.onClick} >Peach</Radio>\n </Col>\n <Col span=\"8\">\n <Radio value=\"watermelon\" onClick={this.onClick} >Watermelon</Radio>\n </Col>\n <Col span=\"8\">\n <Radio value=\"strawberry\" onClick={this.onClick} >Strawberry</Radio>\n </Col>\n </Row>\n <Row>Just simple context</Row>\n </RadioGroup>\n </div>\n );\n }\n}\n\nReactDOM.render(<ControlApp />, mountNode);
Radio
\nRadio buttons allow the user to select a single option from data-set. User can use the radio button for exlusive opration and see all the options side by side. Otherwsie, consider using <DropDown/>
that take up less space than showing all the option.
Param | \nDescripiton | \nType | \nDefault Value | \n
---|---|---|---|
id | \nInput`s id in component | \nString | \n- | \n
checked | \nTo set radio button is checked | \nBoolean | \n- | \n
defaultChecked | \nTo set radio button default to be checked | \nBoolean | \n- | \n
label | \nTo set the radio label | \nString | \n- | \n
onChange | \nCallback on state change signatures: Function(checked: Boolean, e: Event) => void params: checked: {Boolean} Is checked _e_: {Event} Dom Event | \nFunction | \nfunc.noop | \n
onMouseEnter | \nCallback on mouse enter signatures: Function(e: Event) => void params: _e_: {Event} Dom Event | \nFunction | \nfunc.noop | \n
onMouseLeave | \nCallback on mouse leave signatures: Function(e: Event) => void params: _e_: {Event} Dom Event | \nFunction | \nfunc.noop | \n
disabled | \nSet radio button disabel to be used | \nBoolean | \n- | \n
value | \nvalue | \nString/Number/Boolean | \n- | \n
name | \nname | \nString | \n- | \n
Param | \nDescripiton | \nType | \nDefault Value | \n
---|---|---|---|
name | \nname | \nString | \n- | \n
value | \nThe value of the Item witch is selected in radio group | \nString/Number/Boolean | \n- | \n
size | \nUsed with shape prop,valid when shape is set to buttonoption: 'large' 'medium' 'small' | \nEnum | \n'medium' | \n
shape | \nMake radio shape like button, when it set value to 'button' option: 'button' | \nEnum | \n- | \n
defaultValue | \nThe value of the Item witch is default selected in radio group | \nString/Number/Boolean | \n- | \n
onChange | \nCallback on state change signatures: Function(value: String/Number, e: Event) => void params: value: {String/Number} The selected value _e_: {Event} Dom Event | \nFunction | \n() => { } | \n
disabled | \nAll the radios in group are disable to be used | \nBoolean | \n- | \n
dataSource | \nThe data of radio buttons, it can be a String or a Object. For example: ['apple', 'pear', 'orange'] | \nArray<any> | \n[] | \n
children | \nTo set radio button by setting children components | \nArray<ReactElement>/ReactElement | \n- | \n
itemDirection | \nThe direction of item's aligning - hoz: horizonal (default) - ver: vertical Allowed values: 'hoz', 'ver' | \nEnum | \n'hoz' | \n
KeyBoard | \nDescripiton | \n
---|---|
Tab | \nGet the focus, if there is no selection, it is the first one, then you can select it with a space. If it is selected, it will focus on the selected item, and then left-right will navigate and select radio. | \n
单选框
\n单选框允许用户从一个数据集中选择单个选项。如果你觉得用户需要并排看到所有的可选项,使用单选框进行排他操作。此外,考虑使用下拉列表,相对于显示所有的选项占用更少的空间。
\n参数 | \n说明 | \n类型 | \n默认值 | \n
---|---|---|---|
id | \n组件input的id | \nString | \n- | \n
checked | \n设置radio是否选中 | \nBoolean | \n- | \n
defaultChecked | \n设置radio是否默认选中 | \nBoolean | \n- | \n
label | \n通过属性配置label | \nReactNode | \n- | \n
onChange | \n状态变化时触发的事件 签名: Function(checked: Boolean, e: Event) => void 参数: checked: {Boolean} 是否选中 _e_: {Event} Dom 事件对象 | \nFunction | \nfunc.noop | \n
onMouseEnter | \n鼠标进入enter事件 签名: Function(e: Event) => void 参数: _e_: {Event} Dom 事件对象 | \nFunction | \nfunc.noop | \n
onMouseLeave | \n鼠标离开事件 签名: Function(e: Event) => void 参数: _e_: {Event} Dom 事件对象 | \nFunction | \nfunc.noop | \n
disabled | \nradio是否被禁用 | \nBoolean | \n- | \n
value | \nradio 的value | \nString/Number/Boolean | \n- | \n
name | \nname | \nString | \n- | \n
参数 | \n说明 | \n类型 | \n默认值 | \n
---|---|---|---|
name | \nname | \nString | \n- | \n
size | \n与 shape 属性配套使用,shape设为button时有效可选值: 'large'(大) 'medium'(中) 'small'(小) | \nEnum | \n'medium' | \n
shape | \n可以设置成 button 展示形状 可选值: 'button'(按钮状) | \nEnum | \n- | \n
value | \nradio group的选中项的值 | \nString/Number/Boolean | \n- | \n
defaultValue | \nradio group的默认值 | \nString/Number/Boolean | \n- | \n
component | \n设置标签类型 | \nString/Function | \n'div' | \n
onChange | \n选中值改变时的事件 签名: Function(value: String/Number, e: Event) => void 参数: value: {String/Number} 选中项的值 _e_: {Event} Dom 事件对象 | \nFunction | \n() => {} | \n
disabled | \n表示radio被禁用 | \nBoolean | \n- | \n
dataSource | \n可选项列表, 数据项可为 String 或者 Object, 如 ['apple', 'pear', 'orange'] | \nArray<String>/Array<Object> | \n[] | \n
children | \n通过子元素方式设置内部radio | \nArray<ReactElement>/ReactElement | \n- | \n
itemDirection | \n子项目的排列方式 - hoz: 水平排列 (default) - ver: 垂直排列 可选值: 'hoz', 'ver' | \nEnum | \n'hoz' | \n
按键 | \n说明 | \n
---|---|
Tab | \n获取焦点,如果没有任何选中就是第一个,之后可以空格选中。如果有选中的就聚焦到选中项,然后通过左右键直接选中。 | \n
After the slider is focused by Tab or other approaches, you can change its position by pressing the left or right arrows on the keyboard. Currently, only a single slider supports accessibility.
\n","order":"8"},"codes":{"jsx":"import { Range } from '@alifd/next';\n\n\nconst style = {\n marginBottom: '15px'\n};\n\nReactDOM.render(import { Range } from '@alifd/next';\n\n\nconst style = {\n marginBottom: '15px'\n};\n\nReactDOM.render(<div style={{width: '400px', margin: '50px'}}>\n <h4>single slider - from left to right</h4>\n <Range defaultValue={30} style={style} hasTip={false} />\n <h4>single slider - from right to left</h4>\n <Range defaultValue={30} style={style} reverse hasTip={false} />\n </div>, mountNode);
通过Tab键或其他方式使滑块被聚焦之后,可以通过按下键盘的左右箭头来改变滑块的位置,目前只有单滑块支持无障碍。
\n","order":"8"},"codes":{"jsx":"import { Range } from '@alifd/next';\n\n\nconst style = {\n marginBottom: '15px'\n};\n\nReactDOM.render(import { Range } from '@alifd/next';\n\n\nconst style = {\n marginBottom: '15px'\n};\n\nReactDOM.render(<div style={{width: '400px', margin: '50px'}}>\n <h4>single slider - from left to right</h4>\n <Range defaultValue={30} style={style} hasTip={false} />\n <h4>single slider - from right to left</h4>\n <Range defaultValue={30} style={style} reverse hasTip={false} />\n </div>, mountNode);
Basic usage. When slider
is double
, render two sliders; when disabled
is true
, the slider is unusable.
import { Range } from '@alifd/next';\n\n\nconst style = {\n marginBottom: '15px'\n};\n\nReactDOM.render(<div style={{width: '400px', margin: '50px'}}>\n <h4>single slider - from left to right</h4>\n <Range defaultValue={30} style={style} hasTip={false} />\n <h4>single slider - from right to left</h4>\n <Range defaultValue={30} style={style} reverse hasTip={false} />\n <h4>double slider - from outside to inside</h4>\n <Range slider={'double'} defaultValue={[20, 40]} style={style} />\n <h4>double slider - from inside to outside</h4>\n <Range slider={'double'} defaultValue={[20, 40]} style={style} reverse />\n <h4>Disabled</h4>\n <Range defaultValue={30} disabled style={style} />\n <h4>Disabled</h4>\n <Range slider={'double'} defaultValue={[20, 40]} disabled style={style} />\n <h4>tooltipVisible disabled</h4>\n <Range disabled tooltipVisible defaultValue={60} style={style} />\n <h4>tooltipVisible</h4>\n <Range tooltipVisible defaultValue={60} style={style} />\n <h4>tooltipVisible disabled</h4>\n <Range disabled tooltipVisible slider={'double'} defaultValue={[57, 77]} style={style} />\n <h4>tooltipVisible</h4>\n <Range tooltipVisible slider={'double'} defaultValue={[57, 77]} style={style} />\n </div>, mountNode);
基本滑块,当 slider
为 double
时,渲染为双滑块。当 disabled
为 true
时,滑块处于不可用状态。
import { Range } from '@alifd/next';\n\n\nconst style = {\n marginBottom: '15px'\n};\n\nReactDOM.render(<div style={{width: '400px', margin: '50px'}}>\n <h4>single slider - from left to right</h4>\n <Range defaultValue={30} style={style} hasTip={false} />\n <h4>single slider - from right to left</h4>\n <Range defaultValue={30} style={style} reverse hasTip={false} />\n <h4>double slider - from outside to inside</h4>\n <Range slider={'double'} defaultValue={[20, 40]} style={style} />\n <h4>double slider - from inside to outside</h4>\n <Range slider={'double'} defaultValue={[20, 40]} style={style} reverse />\n <h4>Disabled</h4>\n <Range defaultValue={30} disabled style={style} />\n <h4>Disabled</h4>\n <Range slider={'double'} defaultValue={[20, 40]} disabled style={style} />\n <h4>tooltipVisible disabled</h4>\n <Range disabled tooltipVisible defaultValue={60} style={style} />\n <h4>tooltipVisible</h4>\n <Range tooltipVisible defaultValue={60} style={style} />\n <h4>tooltipVisible disabled</h4>\n <Range disabled tooltipVisible slider={'double'} defaultValue={[57, 77]} style={style} />\n <h4>tooltipVisible</h4>\n <Range tooltipVisible slider={'double'} defaultValue={[57, 77]} style={style} />\n </div>, mountNode);
onChange,onProcess callbacks
\n","order":"3"},"codes":{"jsx":"import { Range } from '@alifd/next';\n\nclass App extends React.Component {\n constructor(props) {\n super(props);\n this.state = {\n value: 128,\n value2: 300,\n doubleValue: [200, 300]\n };\n\n }\n\n //Controlled. onChange will be triggered when startValue isn't equal to endValue after sliding\n onChange(value) {\n console.log('onChange value:', value);\n this.setState({value});\n }\n\n // This callback will be triggered when startValue and endValue aren't equal after mousedown/mousemove. You shouldn't call setState here.\n onProcess(value) {\n console.log('onProcess: ', value);\n }\n\n onChangeDouble(doubleValue) {\n console.log('onChange doubleValue:', doubleValue);\n this.setState({doubleValue});\n }\n\n onProcessDouble(doubleValue) {\n console.log('onProcess: ', doubleValue);\n }\n\n render() {\n return (\nrange 0 ~ 1024
\nwith value and without onChange
\ndouble slider controlled
\nrange 0 ~ 1024
\nwith value and without onChange
\ndouble slider controlled
\nimport { Range } from '@alifd/next';\n\nclass App extends React.Component {\n constructor(props) {\n super(props);\n this.state = {\n value: 128,\n value2: 300,\n doubleValue: [200, 300]\n };\n\n }\n\n //Controlled. onChange will be triggered when startValue isn't equal to endValue after sliding\n onChange(value) {\n console.log('onChange value:', value);\n this.setState({value});\n }\n\n // This callback will be triggered when startValue and endValue aren't equal after mousedown/mousemove. You shouldn't call setState here.\n onProcess(value) {\n console.log('onProcess: ', value);\n }\n\n onChangeDouble(doubleValue) {\n console.log('onChange doubleValue:', doubleValue);\n this.setState({doubleValue});\n }\n\n onProcessDouble(doubleValue) {\n console.log('onProcess: ', doubleValue);\n }\n\n render() {\n return (\n <div style={{width: '400px', margin: '50px'}}>\n <p>range 0 ~ 1024</p>\n <div style={{width: '400px', marginTop: '50px'}}>\n\n <Range value={this.state.value} onChange={this.onChange.bind(this)}\n onProcess={this.onProcess.bind(this)}\n min={0} max={1024} marks={[0, 1024]} />\n </div>\n\n <p>with value and without onChange</p>\n <div style={{width: '400px', marginTop: '50px'}}>\n\n <Range value={this.state.value2}\n onProcess={this.onProcess.bind(this)}\n min={0} max={1024} marks={[0, 1024]} />\n </div>\n\n\n <p>double slider controlled</p>\n <div style={{width: '400px', marginTop: '50px'}}>\n\n <Range slider=\"double\" value={this.state.doubleValue} onChange={this.onChangeDouble.bind(this)}\n onProcess={this.onProcessDouble.bind(this)}\n min={0} max={1024} marks={[0, 1024]} />\n </div>\n </div>\n );\n }\n\n}\n\nReactDOM.render(<App />, mountNode);
onChange,onProcess事件
\n","order":"3"},"codes":{"jsx":"import { Range } from '@alifd/next';\n\nclass App extends React.Component {\n constructor(props) {\n super(props);\n this.state = {\n value: 128,\n value2: 300,\n doubleValue: [200, 300]\n };\n\n }\n\n //Controlled. onChange will be triggered when startValue isn't equal to endValue after sliding\n onChange(value) {\n console.log('onChange value:', value);\n this.setState({value});\n }\n\n // This callback will be triggered when startValue and endValue aren't equal after mousedown/mousemove. You shouldn't call setState here.\n onProcess(value) {\n console.log('onProcess: ', value);\n }\n\n onChangeDouble(doubleValue) {\n console.log('onChange doubleValue:', doubleValue);\n this.setState({doubleValue});\n }\n\n onProcessDouble(doubleValue) {\n console.log('onProcess: ', doubleValue);\n }\n\n render() {\n return (\nrange 0 ~ 1024
\nwith value and without onChange
\ndouble slider controlled
\nrange 0 ~ 1024
\nwith value and without onChange
\ndouble slider controlled
\nimport { Range } from '@alifd/next';\n\nclass App extends React.Component {\n constructor(props) {\n super(props);\n this.state = {\n value: 128,\n value2: 300,\n doubleValue: [200, 300]\n };\n\n }\n\n //Controlled. onChange will be triggered when startValue isn't equal to endValue after sliding\n onChange(value) {\n console.log('onChange value:', value);\n this.setState({value});\n }\n\n // This callback will be triggered when startValue and endValue aren't equal after mousedown/mousemove. You shouldn't call setState here.\n onProcess(value) {\n console.log('onProcess: ', value);\n }\n\n onChangeDouble(doubleValue) {\n console.log('onChange doubleValue:', doubleValue);\n this.setState({doubleValue});\n }\n\n onProcessDouble(doubleValue) {\n console.log('onProcess: ', doubleValue);\n }\n\n render() {\n return (\n <div style={{width: '400px', margin: '50px'}}>\n <p>range 0 ~ 1024</p>\n <div style={{width: '400px', marginTop: '50px'}}>\n\n <Range value={this.state.value} onChange={this.onChange.bind(this)}\n onProcess={this.onProcess.bind(this)}\n min={0} max={1024} marks={[0, 1024]} />\n </div>\n\n <p>with value and without onChange</p>\n <div style={{width: '400px', marginTop: '50px'}}>\n\n <Range value={this.state.value2}\n onProcess={this.onProcess.bind(this)}\n min={0} max={1024} marks={[0, 1024]} />\n </div>\n\n\n <p>double slider controlled</p>\n <div style={{width: '400px', marginTop: '50px'}}>\n\n <Range slider=\"double\" value={this.state.doubleValue} onChange={this.onChangeDouble.bind(this)}\n onProcess={this.onProcessDouble.bind(this)}\n min={0} max={1024} marks={[0, 1024]} />\n </div>\n </div>\n );\n }\n\n}\n\nReactDOM.render(<App />, mountNode);
Used with number-picker to set the icon.
\n","order":"5"},"codes":{"jsx":"import { Range, NumberPicker, Grid, Icon } from '@alifd/next';\n\n\n\nconst {Row, Col} = Grid;\n\nclass Demo extends React.Component {\n constructor(props, context) {\n super(props, context);\n this.state = {\n valueInt: 3,\n valueDec: 0.05,\n valueIcon: 1,\n preIconClass: '',\n afterIconClass: ''\n };\n\n }\n\n onChangeInt(value) {\n console.log(value);\n this.setState(Object.assign({}, this.state, {\n valueInt: value\n }));\n }\n\n onChangeDec(value) {\n\n this.setState(Object.assign({}, this.state, {\n valueDec: value\n }));\n }\n\n onIconRangeProcess(value) {\n const mid = 50;\n this.setState(Object.assign({}, this.state, {\n valueIcon: value,\n preIconClass: value < mid ? 'myicon-highlight' : '',\n afterIconClass: value >= mid ? 'myicon-highlight' : ''\n }));\n }\n\n render() {\n return (\nimport { Range, NumberPicker, Grid, Icon } from '@alifd/next';\n\n\n\nconst {Row, Col} = Grid;\n\nclass Demo extends React.Component {\n constructor(props, context) {\n super(props, context);\n this.state = {\n valueInt: 3,\n valueDec: 0.05,\n valueIcon: 1,\n preIconClass: '',\n afterIconClass: ''\n };\n\n }\n\n onChangeInt(value) {\n console.log(value);\n this.setState(Object.assign({}, this.state, {\n valueInt: value\n }));\n }\n\n onChangeDec(value) {\n\n this.setState(Object.assign({}, this.state, {\n valueDec: value\n }));\n }\n\n onIconRangeProcess(value) {\n const mid = 50;\n this.setState(Object.assign({}, this.state, {\n valueIcon: value,\n preIconClass: value < mid ? 'myicon-highlight' : '',\n afterIconClass: value >= mid ? 'myicon-highlight' : ''\n }));\n }\n\n render() {\n return (\n <div style={{width: '400px', margin: '50px'}}>\n <h2>Used with numberPicker</h2>\n <Row>\n <Col span=\"12\" style={{marginTop: '10px'}}>\n <Range value={this.state.valueInt} min={0} max={20} step={1}\n onChange={this.onChangeInt.bind(this)} />\n </Col>\n <Col span=\"12\">\n <NumberPicker value={this.state.valueInt} min={0} max={1024} step={1}\n onChange={this.onChangeInt.bind(this)} />\n </Col>\n </Row>\n <br />\n <Row>\n <Col span=\"12\" style={{marginTop: '10px'}}>\n <Range value={this.state.valueDec} min={0} max={1} step={0.01}\n onChange={this.onChangeDec.bind(this)} />\n </Col>\n <Col span=\"12\">\n <NumberPicker value={this.state.valueDec} min={0} max={1} step={0.01}\n onChange={this.onChangeDec.bind(this)} />\n </Col>\n </Row>\n <h2>Used with Icon</h2>\n\n <div className=\"iconWrapper\">\n <Icon className={`myicon ${this.state.preIconClass}`} type=\"cry\" />\n <Range min={1} max={100} onChange={this.onIconRangeProcess.bind(this)} value={this.state.valueIcon} />\n <Icon className={`myicon ${this.state.afterIconClass}`} type=\"smile\" />\n </div>\n </div>\n );\n }\n\n\n}\n\nReactDOM.render(<Demo />, mountNode);\n\n
.iconWrapper {\n position: relative;\n padding: 0px 40px;\n}\n\n.iconWrapper .myicon {\n position: absolute;\n top: -3px;\n width: 16px;\n height: 16px;\n line-height: 1;\n font-size: 16px;\n color: #ccc;\n}\n\n.iconWrapper .myicon:first-child {\n left: 0;\n}\n\n.iconWrapper .myicon:last-child {\n right: 0;\n}\n\n.myicon.myicon-highlight {\n color: #666;\n}
与number-picker结合,外部控制,与Icon结合设置边界Icon
\n","order":"5"},"codes":{"jsx":"import { Range, NumberPicker, Grid, Icon } from '@alifd/next';\n\n\n\nconst {Row, Col} = Grid;\n\nclass Demo extends React.Component {\n constructor(props, context) {\n super(props, context);\n this.state = {\n valueInt: 3,\n valueDec: 0.05,\n valueIcon: 1,\n preIconClass: '',\n afterIconClass: ''\n };\n\n }\n\n onChangeInt(value) {\n console.log(value);\n this.setState(Object.assign({}, this.state, {\n valueInt: value\n }));\n }\n\n onChangeDec(value) {\n\n this.setState(Object.assign({}, this.state, {\n valueDec: value\n }));\n }\n\n onIconRangeProcess(value) {\n const mid = 50;\n this.setState(Object.assign({}, this.state, {\n valueIcon: value,\n preIconClass: value < mid ? 'myicon-highlight' : '',\n afterIconClass: value >= mid ? 'myicon-highlight' : ''\n }));\n }\n\n render() {\n return (\nimport { Range, NumberPicker, Grid, Icon } from '@alifd/next';\n\n\n\nconst {Row, Col} = Grid;\n\nclass Demo extends React.Component {\n constructor(props, context) {\n super(props, context);\n this.state = {\n valueInt: 3,\n valueDec: 0.05,\n valueIcon: 1,\n preIconClass: '',\n afterIconClass: ''\n };\n\n }\n\n onChangeInt(value) {\n console.log(value);\n this.setState(Object.assign({}, this.state, {\n valueInt: value\n }));\n }\n\n onChangeDec(value) {\n\n this.setState(Object.assign({}, this.state, {\n valueDec: value\n }));\n }\n\n onIconRangeProcess(value) {\n const mid = 50;\n this.setState(Object.assign({}, this.state, {\n valueIcon: value,\n preIconClass: value < mid ? 'myicon-highlight' : '',\n afterIconClass: value >= mid ? 'myicon-highlight' : ''\n }));\n }\n\n render() {\n return (\n <div style={{width: '400px', margin: '50px'}}>\n <h2>Used with numberPicker</h2>\n <Row>\n <Col span=\"12\" style={{marginTop: '10px'}}>\n <Range value={this.state.valueInt} min={0} max={20} step={1}\n onChange={this.onChangeInt.bind(this)} />\n </Col>\n <Col span=\"12\">\n <NumberPicker value={this.state.valueInt} min={0} max={1024} step={1}\n onChange={this.onChangeInt.bind(this)} />\n </Col>\n </Row>\n <br />\n <Row>\n <Col span=\"12\" style={{marginTop: '10px'}}>\n <Range value={this.state.valueDec} min={0} max={1} step={0.01}\n onChange={this.onChangeDec.bind(this)} />\n </Col>\n <Col span=\"12\">\n <NumberPicker value={this.state.valueDec} min={0} max={1} step={0.01}\n onChange={this.onChangeDec.bind(this)} />\n </Col>\n </Row>\n <h2>Used with Icon</h2>\n\n <div className=\"iconWrapper\">\n <Icon className={`myicon ${this.state.preIconClass}`} type=\"cry\" />\n <Range min={1} max={100} onChange={this.onIconRangeProcess.bind(this)} value={this.state.valueIcon} />\n <Icon className={`myicon ${this.state.afterIconClass}`} type=\"smile\" />\n </div>\n </div>\n );\n }\n\n\n}\n\nReactDOM.render(<Demo />, mountNode);\n\n
.iconWrapper {\n position: relative;\n padding: 0px 40px;\n}\n\n.iconWrapper .myicon {\n position: absolute;\n top: -3px;\n width: 16px;\n height: 16px;\n line-height: 1;\n font-size: 16px;\n color: #ccc;\n}\n\n.iconWrapper .myicon:first-child {\n left: 0;\n}\n\n.iconWrapper .myicon:last-child {\n right: 0;\n}\n\n.myicon.myicon-highlight {\n color: #666;\n}
It means slider
is double
, and defaultValue
is a interval. The scope can not be changed, drag the selected area to change the position of the start and end slider.
range 0 ~ 1024
\nrange 0 ~ 1024
\nimport { Range } from '@alifd/next';\n\nconst style = {\n marginBottom: '15px'\n};\n\nconst styleX3 = {\n marginBottom: '45px'\n};\n\nclass App extends React.Component {\n constructor(props) {\n super(props);\n this.state = {\n value: [10, 300]\n };\n\n }\n\n //Controlled. onChange will be triggered when startValue isn't equal to endValue after sliding\n onChange(value) {\n console.log('onChange value:', value);\n this.setState({value});\n }\n\n // This callback will be triggered when startValue and endValue aren't equal after mousedown/mousemove. You shouldn't call setState here.\n onProcess(value) {\n // this.setState({value});\n console.log('onProcess: ', value);\n }\n\n render() {\n return (\n <div style={{width: '400px', margin: '50px'}}>\n <h4>fixedWidth basic</h4>\n <Range fixedWidth defaultValue={[20, 40]} style={style} />\n <h4>fixedWidth basic with tooltipVisible</h4>\n <Range tooltipVisible fixedWidth defaultValue={[70, 90]} style={styleX3} />\n <Range disabled tooltipVisible fixedWidth defaultValue={[70, 90]} style={style} />\n <h4>fixedWidth with marks</h4>\n <Range fixedWidth step={10} defaultValue={[20, 40]} scales={10} marks={10} style={styleX3} />\n <Range fixedWidth step={2} defaultValue={[60, 80]} scales={[0, 100]} marks={[0, 30, 100]} style={style} marksPosition=\"below\" />\n <h4>fixedWidth with 0.01 step</h4>\n <Range fixedWidth defaultValue={[0.6, 0.7]} min={0.5} max={1} step={0.01}/>\n <div style={{width: '400px', marginTop: '50px'}}>\n <p>range 0 ~ 1024</p>\n <Range fixedWidth value={this.state.value}\n onChange={this.onChange.bind(this)}\n onProcess={this.onProcess.bind(this)}\n min={0} max={1024} marks={[0, 1024]} />\n </div>\n </div>\n );\n }\n\n}\n\nReactDOM.render(<App />, mountNode);\n
默认双滑块(slider
为 double
),且指定 defaultValue
为区间值下可用。范围不可被改变,拖动所选区域改变始末滑块位置。
range 0 ~ 1024
\nrange 0 ~ 1024
\nimport { Range } from '@alifd/next';\n\nconst style = {\n marginBottom: '15px'\n};\n\nconst styleX3 = {\n marginBottom: '45px'\n};\n\nclass App extends React.Component {\n constructor(props) {\n super(props);\n this.state = {\n value: [10, 300]\n };\n\n }\n\n //Controlled. onChange will be triggered when startValue isn't equal to endValue after sliding\n onChange(value) {\n console.log('onChange value:', value);\n this.setState({value});\n }\n\n // This callback will be triggered when startValue and endValue aren't equal after mousedown/mousemove. You shouldn't call setState here.\n onProcess(value) {\n // this.setState({value});\n console.log('onProcess: ', value);\n }\n\n render() {\n return (\n <div style={{width: '400px', margin: '50px'}}>\n <h4>fixedWidth basic</h4>\n <Range fixedWidth defaultValue={[20, 40]} style={style} />\n <h4>fixedWidth basic with tooltipVisible</h4>\n <Range tooltipVisible fixedWidth defaultValue={[70, 90]} style={styleX3} />\n <Range disabled tooltipVisible fixedWidth defaultValue={[70, 90]} style={style} />\n <h4>fixedWidth with marks</h4>\n <Range fixedWidth step={10} defaultValue={[20, 40]} scales={10} marks={10} style={styleX3} />\n <Range fixedWidth step={2} defaultValue={[60, 80]} scales={[0, 100]} marks={[0, 30, 100]} style={style} marksPosition=\"below\" />\n <h4>fixedWidth with 0.01 step</h4>\n <Range fixedWidth defaultValue={[0.6, 0.7]} min={0.5} max={1} step={0.01}/>\n <div style={{width: '400px', marginTop: '50px'}}>\n <p>range 0 ~ 1024</p>\n <Range fixedWidth value={this.state.value}\n onChange={this.onChange.bind(this)}\n onProcess={this.onProcess.bind(this)}\n min={0} max={1024} marks={[0, 1024]} />\n </div>\n </div>\n );\n }\n\n}\n\nReactDOM.render(<App />, mountNode);\n
Use scales
and marks
to set scales and marks
With minimal and maximal value
\nBelow
\nEqual division
\nFree
\nWith minimal and maximal value
\nBelow
\nEqual division
\nFree
\nimport { Range } from '@alifd/next';\n\nconst style = {\n marginBottom: '20px',\n marginTop: '20px'\n};\n\nReactDOM.render(<div style={{width: '400px', margin: '50px'}}>\n <p>With minimal and maximal value</p>\n <Range defaultValue={0} marks={[0, 100]} style={style} />\n <Range slider={'double'} defaultValue={[20, 40]} scales={[0, 100]} marks={[0, 100]} style={style} />\n <Range defaultValue={30} style={style} />\n <p>Below</p>\n <Range defaultValue={0} marks={[0, 100]} style={style} marksPosition=\"below\" />\n <Range slider={'double'} defaultValue={[20, 40]} scales={[0, 100]} marks={[0, 100]} style={style} marksPosition=\"below\" />\n <Range defaultValue={30} scales={[0, 100]} marks={[0, 100]} style={style} marksPosition=\"below\" />\n <p>Equal division</p>\n <Range defaultValue={30} marks={5} style={style} />\n <Range slider={'double'} defaultValue={[20, 40]} scales={10} marks={10} style={style} />\n <Range disabled slider={'double'} defaultValue={[20, 40]} scales={10} marks={10} style={style} />\n <p>Free</p>\n <Range defaultValue={30} marks={[0, 26, 37, 100]} style={style} />\n <Range slider={'double'} defaultValue={[20, 40]} marks={[0, 26, 37, 100]} style={style} hasTip={false}/>\n <Range defaultValue={30} marks={{0: '0°C', 26: '26°C', 37: '37°C', 100: '100°C'}} style={style} />\n </div>, mountNode);
通过 scales
与 marks
属性设置刻度及标识。
With minimal and maximal value
\nBelow
\nEqual division
\nFree
\nWith minimal and maximal value
\nBelow
\nEqual division
\nFree
\nimport { Range } from '@alifd/next';\n\nconst style = {\n marginBottom: '20px',\n marginTop: '20px'\n};\n\nReactDOM.render(<div style={{width: '400px', margin: '50px'}}>\n <p>With minimal and maximal value</p>\n <Range defaultValue={0} marks={[0, 100]} style={style} />\n <Range slider={'double'} defaultValue={[20, 40]} scales={[0, 100]} marks={[0, 100]} style={style} />\n <Range defaultValue={30} style={style} />\n <p>Below</p>\n <Range defaultValue={0} marks={[0, 100]} style={style} marksPosition=\"below\" />\n <Range slider={'double'} defaultValue={[20, 40]} scales={[0, 100]} marks={[0, 100]} style={style} marksPosition=\"below\" />\n <Range defaultValue={30} scales={[0, 100]} marks={[0, 100]} style={style} marksPosition=\"below\" />\n <p>Equal division</p>\n <Range defaultValue={30} marks={5} style={style} />\n <Range slider={'double'} defaultValue={[20, 40]} scales={10} marks={10} style={style} />\n <Range disabled slider={'double'} defaultValue={[20, 40]} scales={10} marks={10} style={style} />\n <p>Free</p>\n <Range defaultValue={30} marks={[0, 26, 37, 100]} style={style} />\n <Range slider={'double'} defaultValue={[20, 40]} marks={[0, 26, 37, 100]} style={style} hasTip={false}/>\n <Range defaultValue={30} marks={{0: '0°C', 26: '26°C', 37: '37°C', 100: '100°C'}} style={style} />\n </div>, mountNode);
Used with min
(defaults to 0) and max
(defaults to 100) to set the boundary and step
to set the step.
Range 0 ~ 1024
\nRange 0 ~ 1024,step 128
\nRange 0 ~ 1024
\nRange 0 ~ 1024,step 128
\nimport { Range } from '@alifd/next';\n\nconst style = {\n marginBottom: '40px',\n marginTop: '40px'\n};\nReactDOM.render(\n <div style={{width: '400px', margin: '50px'}}>\n <p>Range 0 ~ 1024</p>\n <Range defaultValue={128} min={0} max={1024} marks={[0, 1024]} style={style} />\n <p>Range 0 ~ 1024,step 128</p>\n <Range defaultValue={512} min={0} max={1024} step={128} marks={[0, 1024]}\n style={style} />\n </div>\n, mountNode);
可以通过 min
与 max
设置范围边界。通过 step
(被 max - min 整除) 设置移动的最小步频。min默认为0,max默认为100.
Range 0 ~ 1024
\nRange 0 ~ 1024,step 128
\nRange 0 ~ 1024
\nRange 0 ~ 1024,step 128
\nimport { Range } from '@alifd/next';\n\nconst style = {\n marginBottom: '40px',\n marginTop: '40px'\n};\nReactDOM.render(\n <div style={{width: '400px', margin: '50px'}}>\n <p>Range 0 ~ 1024</p>\n <Range defaultValue={128} min={0} max={1024} marks={[0, 1024]} style={style} />\n <p>Range 0 ~ 1024,step 128</p>\n <Range defaultValue={512} min={0} max={1024} step={128} marks={[0, 1024]}\n style={style} />\n </div>\n, mountNode);
When reverse is set to true, the selected part is reversed.
\n","order":"7"},"codes":{"jsx":"import { Range } from '@alifd/next';\n\n\nconst style = {\n marginBottom: '15px'\n};\n\nReactDOM.render(\nimport { Range } from '@alifd/next';\n\n\nconst style = {\n marginBottom: '15px'\n};\n\nReactDOM.render(\n <div style={{width: '400px', margin: '50px'}}>\n <Range defaultValue={30} style={style} hasTip={false} />\n <Range defaultValue={30} style={style} reverse hasTip={false} />\n <Range slider={'double'} defaultValue={[20, 40]} style={style} />\n <Range slider={'double'} defaultValue={[20, 40]} style={style} reverse />\n <Range defaultValue={30} disabled style={style} />\n <Range defaultValue={30} disabled style={style} reverse />\n <Range slider={'double'} defaultValue={[20, 40]} disabled style={style} />\n <Range slider={'double'} defaultValue={[20, 40]} disabled style={style} reverse />\n </div>, mountNode);
设置reverse为true, 选中态会反转。
\n","order":"7"},"codes":{"jsx":"import { Range } from '@alifd/next';\n\n\nconst style = {\n marginBottom: '15px'\n};\n\nReactDOM.render(\nimport { Range } from '@alifd/next';\n\n\nconst style = {\n marginBottom: '15px'\n};\n\nReactDOM.render(\n <div style={{width: '400px', margin: '50px'}}>\n <Range defaultValue={30} style={style} hasTip={false} />\n <Range defaultValue={30} style={style} reverse hasTip={false} />\n <Range slider={'double'} defaultValue={[20, 40]} style={style} />\n <Range slider={'double'} defaultValue={[20, 40]} style={style} reverse />\n <Range defaultValue={30} disabled style={style} />\n <Range defaultValue={30} disabled style={style} reverse />\n <Range slider={'double'} defaultValue={[20, 40]} disabled style={style} />\n <Range slider={'double'} defaultValue={[20, 40]} disabled style={style} reverse />\n </div>, mountNode);
tipRender demo.
\n","order":"5"},"codes":{"jsx":"import { Range } from '@alifd/next';\n\nclass App extends React.Component {\n constructor(props) {\n super(props);\n this.state = {\n value: 128\n };\n\n }\n\n // This callback will be triggered when startValue and endValue aren't equal after moving.\n onChange(value) {\n console.log('onChange value:', value);\n }\n\n // This callback will be triggered when startValue and endValue aren't equal after mousedown/mousemove. You can call setState here when using a controlled component.\n onProcess(value) {\n console.log('onProcess');\n this.setState({value});\n }\n\n formatter(value) {\n return `$${value}`;\n }\n render() {\n return (\nRange 0 ~ 1024
\nRange 0 ~ 1024
\nimport { Range } from '@alifd/next';\n\nclass App extends React.Component {\n constructor(props) {\n super(props);\n this.state = {\n value: 128\n };\n\n }\n\n // This callback will be triggered when startValue and endValue aren't equal after moving.\n onChange(value) {\n console.log('onChange value:', value);\n }\n\n // This callback will be triggered when startValue and endValue aren't equal after mousedown/mousemove. You can call setState here when using a controlled component.\n onProcess(value) {\n console.log('onProcess');\n this.setState({value});\n }\n\n formatter(value) {\n return `$${value}`;\n }\n render() {\n return (\n <div style={{width: '400px', margin: '50px'}}>\n <p>Range 0 ~ 1024</p>\n <div style={{width: '400px', marginTop: '50px'}}>\n\n <Range defaultValue={256} tipRender={this.formatter.bind(this)} value={this.state.value} onChange={this.onChange.bind(this)}\n onProcess={this.onProcess.bind(this)}\n min={0} max={1024} marks={[0, 1024]} />\n </div>\n </div>\n );\n }\n\n}\n\nReactDOM.render(<App />, mountNode);
tipRender 示例
\n","order":"5"},"codes":{"jsx":"import { Range } from '@alifd/next';\n\nclass App extends React.Component {\n constructor(props) {\n super(props);\n this.state = {\n value: 128\n };\n\n }\n\n // This callback will be triggered when startValue and endValue aren't equal after moving.\n onChange(value) {\n console.log('onChange value:', value);\n }\n\n // This callback will be triggered when startValue and endValue aren't equal after mousedown/mousemove. You can call setState here when using a controlled component.\n onProcess(value) {\n console.log('onProcess');\n this.setState({value});\n }\n\n formatter(value) {\n return `$${value}`;\n }\n render() {\n return (\nRange 0 ~ 1024
\nRange 0 ~ 1024
\nimport { Range } from '@alifd/next';\n\nclass App extends React.Component {\n constructor(props) {\n super(props);\n this.state = {\n value: 128\n };\n\n }\n\n // This callback will be triggered when startValue and endValue aren't equal after moving.\n onChange(value) {\n console.log('onChange value:', value);\n }\n\n // This callback will be triggered when startValue and endValue aren't equal after mousedown/mousemove. You can call setState here when using a controlled component.\n onProcess(value) {\n console.log('onProcess');\n this.setState({value});\n }\n\n formatter(value) {\n return `$${value}`;\n }\n render() {\n return (\n <div style={{width: '400px', margin: '50px'}}>\n <p>Range 0 ~ 1024</p>\n <div style={{width: '400px', marginTop: '50px'}}>\n\n <Range defaultValue={256} tipRender={this.formatter.bind(this)} value={this.state.value} onChange={this.onChange.bind(this)}\n onProcess={this.onProcess.bind(this)}\n min={0} max={1024} marks={[0, 1024]} />\n </div>\n </div>\n );\n }\n\n}\n\nReactDOM.render(<App />, mountNode);
Range
\nRange Component is used to select a value in a range by dragging slider. Normally, the minimal value of the range is placed on the leftmost, and the maximal is on the rightmost. Sometimes, icons can be placed at the ends to reflect the strength. Range Component is the best choice when setting volume, brightness or saturation that related to strength.
\nParam | \nDescripiton | \nType | \nDefault Value | \n
---|---|---|---|
slider | \nnumber of sliders option: 'single' 'double' | \nEnum | \n'single' | \n
min | \nminimal value | \nNumber | \n0 | \n
max | \nmaximal value | \nNumber | \n100 | \n
step | \nstep of the range, which is positive integer and (max - min) can be divided by it | \nNumber | \n1 | \n
value | \ncurrent value. It's in the form of Number when slider is single otherwise [Number, Number] | \nNumber/Array<Number> | \n- | \n
defaultValue | \ndefault value. It's in the form of Number when slider is single otherwise [Number, Number] | \nNumber/Array<Number> | \n- | \n
marks | \nway to show the scale. (false means nothing, array means enum, number means equal division, and object means key as the mark with value as the value) | \nBoolean/Number/Array<Number>/Object | \nfalse | \n
marksPosition | \nposition for the scale option: 'above', 'below' | \nEnum | \n'above' | \n
disabled | \ndisabled | \nBoolean | \nfalse | \n
onChange | \ncallback triggered when value changes signature: Function(value: String/number) => void parameter: value: {String/number} null | \nFunction | \nfunc.noop | \n
onProcess | \ncallback triggered when slider being dragged, and used only for special need signature: Function(value: String/number) => void parameter: value: {String/number} null | \nFunction | \nfunc.noop | \n
hasTip | \nwhether to show tip | \nBoolean | \ntrue | \n
tipRender | \ncustom tip content signature: Function(value: Number/String) => ReactNode signature: value: {Number/String} value returns: {ReactNode} content | \nFunction | \nvalue => value | \n
reverse | \nreverse the selected part | \nBoolean | \nfalse | \n
pure | \npure render or not | \nBoolean | \nfalse | \n
fixedWidth | \ndrag a line with fixed width. It considers slider as double , and defaultValue must be a interval. | \nBoolean | \nfalse | \n
tooltipVisible | \ntooltip always be visible or not | \nBoolean | \nfalse | \n
KeyBoard | \nDescripiton | \n
---|---|
Right Arrow | \ncontrol the slider to move to the right | \n
Left Arrow | \ncontrol the slider to move to the left | \n
Tab | \nswitch to other slider | \n
区间选择
\n滑块控件(Sliders,简称滑块)可以让我们通过在连续或间断的区间内滑动锚点来选择一个合适的数值。区间最小值放在左边,对应的,最大值放在右边。滑块(Sliders)可以在滑动条的左右两端设定图标来反映数值的强度。这种交互特性使得它在设置诸如音量、亮度、色彩饱和度等需要反映强度等级的选项时成为一种极好的选择。
\n参数 | \n说明 | \n类型 | \n默认值 | \n
---|---|---|---|
slider | \n滑块个数 可选值: 'single'(单个) 'double'(两个) | \nEnum | \n'single' | \n
min | \n最小值 | \nNumber | \n0 | \n
max | \n最大值 | \nNumber | \n100 | \n
step | \n步长,取值必须大于 0,并且可被 (max - min) 整除。 | \nNumber | \n1 | \n
value | \n设置当前取值。当 slider 为 single 时,使用 Number ,否则用 [Number, Number] | \nNumber/Array<Number> | \n- | \n
defaultValue | \n设置初始取值。当 slider 为 single 时,使用 Number ,否则用 [Number, Number] | \nNumber/Array<Number> | \n- | \n
marks | \n刻度数值显示逻辑(false 代表不显示,array 枚举显示的值,number 代表按 number 平分,object 表示按 key 划分,value 值显示) | \nBoolean/Number/Array<Number>/Object | \nfalse | \n
marksPosition | \nmarks显示在上方('above')or下方('below') 可选值: 'above', 'below' | \nEnum | \n'above' | \n
disabled | \n值为 true 时,滑块为禁用状态 | \nBoolean | \nfalse | \n
onChange | \n当 Range 的值发生改变后,会触发 onChange 事件,并把改变后的值作为参数传入, 如果设置了value, 要配合此函数做受控使用 签名: Function(value: String/number) => void 参数: value: {String/number} null | \nFunction | \nfunc.noop | \n
onProcess | \n滑块拖动的时候触发的事件,不建议在这里setState, 一般情况下不需要用, 滑动时有特殊需求时使用 签名: Function(value: String/number) => void 参数: value: {String/number} null | \nFunction | \nfunc.noop | \n
hasTip | \n是否显示 tip | \nBoolean | \ntrue | \n
tipRender | \n自定义 tip 显示内容 签名: Function(value: Number/String) => ReactNode 参数: value: {Number/String} 值 返回值: {ReactNode} 显示内容 | \nFunction | \nvalue => value | \n
reverse | \n选中态反转 | \nBoolean | \nfalse | \n
pure | \n是否pure render | \nBoolean | \nfalse | \n
fixedWidth | \n是否为拖动线段类型,默认slider为double, defaultValue必传且指定区间 | \nBoolean | \nfalse | \n
tooltipVisible | \ntooltip是否默认展示 | \nBoolean | \nfalse | \n
rtl | \n是否已rtl模式展示 | \nBoolean | \nfalse | \n
按键 | \n说明 | \n
---|---|
Right Arrow | \n控制滑块往右移动 | \n
Left Arrow | \n控制滑块向左移动 | \n
Tab | \n切换滑动条 | \n
To Support accessibility, you should assign an id prop to Rating. Notice: Don't assign same id prop for more than one Rating.
\n","order":"5"},"codes":{"jsx":"import { Rating } from '@alifd/next';\n\nconst starMap = {\n 1: 'Bad',\n 2: 'OK',\n 3: 'Good',\n 4: 'Great',\n 5: 'Perfect'\n};\nReactDOM.render(import { Rating } from '@alifd/next';\n\nconst starMap = {\n 1: 'Bad',\n 2: 'OK',\n 3: 'Good',\n 4: 'Great',\n 5: 'Perfect'\n};\nReactDOM.render(<div>\n <Rating\n id=\"rating-a11y-1\"\n defaultValue={3}\n readAs={(val) => starMap[val]}\n onChange={val => console.log('change:', val)}\n onHoverChange={val => console.log('hover:', val)} />\n</div>, mountNode);
组件内置了部分支持无障碍, 但是额外需要开发者手动事情才能完整支持无障碍:给 Rating 传入一个id,就可以支持语音提示当前选择的评分。注意:如果一个页面上有多个 Rating,id 属性一定不能相同。
\n","order":"5"},"codes":{"jsx":"import { Rating } from '@alifd/next';\n\nconst starMap = {\n 1: 'Bad',\n 2: 'OK',\n 3: 'Good',\n 4: 'Great',\n 5: 'Perfect'\n};\nReactDOM.render(import { Rating } from '@alifd/next';\n\nconst starMap = {\n 1: 'Bad',\n 2: 'OK',\n 3: 'Good',\n 4: 'Great',\n 5: 'Perfect'\n};\nReactDOM.render(<div>\n <Rating\n id=\"rating-a11y-1\"\n defaultValue={3}\n readAs={(val) => starMap[val]}\n onChange={val => console.log('change:', val)}\n onHoverChange={val => console.log('hover:', val)} />\n</div>, mountNode);
Basic usage.
\n","order":"0"},"codes":{"jsx":"import { Rating } from '@alifd/next';\n\nReactDOM.render(import { Rating } from '@alifd/next';\n\nReactDOM.render(<div>\n <Rating defaultValue={3.2} onChange={val => console.log('change:', val)} onHoverChange={val => console.log('hover:', val)} />\n</div>, mountNode);
最简单的用法。
\n","order":"0"},"codes":{"jsx":"import { Rating } from '@alifd/next';\n\nReactDOM.render(import { Rating } from '@alifd/next';\n\nReactDOM.render(<div>\n <Rating defaultValue={3.2} onChange={val => console.log('change:', val)} onHoverChange={val => console.log('hover:', val)} />\n</div>, mountNode);
Rating component can only display score when you set disabled
attribute.
import { Rating } from '@alifd/next';\n\nReactDOM.render(<Rating defaultValue={3.2} disabled />, mountNode);
设置 disabled
属性后,评分组件仅展示模式,不可选择。
import { Rating } from '@alifd/next';\n\nReactDOM.render(<Rating defaultValue={3.2} disabled />, mountNode);
Rating component display grade tips when you set showGrade
attribute.
import { Rating } from '@alifd/next';\n\nconst starMap = {\n 1: 'Bad',\n 2: 'OK',\n 3: 'Good',\n 4: 'Great',\n 5: 'Perfect'\n};\n\nReactDOM.render(\n <Rating\n defaultValue={2}\n showGrade\n readAs={(val) => starMap[val]}\n />, mountNode);
添加 showGrade
属性,使评分组件具有等级提示信息。
import { Rating } from '@alifd/next';\n\nconst starMap = {\n 1: 'Bad',\n 2: 'OK',\n 3: 'Good',\n 4: 'Great',\n 5: 'Perfect'\n};\n\nReactDOM.render(\n <Rating\n defaultValue={2}\n showGrade\n readAs={(val) => starMap[val]}\n />, mountNode);
Rating component only support integer score in default situation, bu you can set allowHalf
attribute to support half star.
import { Rating } from '@alifd/next';\n\nReactDOM.render(<Rating defaultValue={3.2} allowHalf />, mountNode);
默认情况下评分组件只支持整数评分,通过开启 allowHalf
属性可以支持半星评分。
import { Rating } from '@alifd/next';\n\nReactDOM.render(<Rating defaultValue={3.2} allowHalf />, mountNode);
You can control the size of rating component by size
attribute, and there are three options: small
, medium
, large
, the default value is medium
.
import { Rating } from '@alifd/next';\n\nReactDOM.render(<div>\n <Rating defaultValue={3.2} size=\"small\" />\n <br/>\n <br/>\n <Rating defaultValue={3.2} />\n <br/>\n <br/>\n <Rating defaultValue={3.2} size=\"large\" />\n</div>, mountNode);
通过 size
属性可以控制评分组件的大小,支持三种尺寸 small
, medium
, large
。\n默认尺寸为 medium
。
import { Rating } from '@alifd/next';\n\nReactDOM.render(<div>\n <Rating defaultValue={3.2} size=\"small\" />\n <br/>\n <br/>\n <Rating defaultValue={3.2} />\n <br/>\n <br/>\n <Rating defaultValue={3.2} size=\"large\" />\n</div>, mountNode);
Rating component is usually used for customer feedback.
\nParam | \nDescripiton | \nType | \nDefault Value | \n
---|---|---|---|
defaultValue | \ndefault value | \nNumber | \n0 | \n
size | \nsize options: 'small', 'medium', 'large' | \nEnum | \n'medium' | \n
value | \nvalue | \nNumber | \n- | \n
count | \nfull mark of rating | \nNumber | \n5 | \n
showGrade | \ndisplay grade or not | \nBoolean | \nfalse | \n
allowHalf | \nallow half start or not | \nBoolean | \nfalse | \n
onChange | \ncallback function on click star signatures: Function(value: String) => void params: value: {String} score | \nFunction | \nfunc.noop | \n
onHoverChange | \ncallback function on hover star signatures: Function(value: String) => void params: value: {String} score | \nFunction | \nfunc.noop | \n
disabled | \ndisabled rate or not | \nBoolean | \nfalse | \n
readAs | \ncustom display of grade signatures: Function() => void | \nFunction | \nval => val | \n
KeyBoard | \nDescripiton | \n
---|---|
Up Arrow | \nincrease star rating | \n
Down Arrow | \ndecrease star rating | \n
Right Arrow | \nincrease star rating | \n
Left Arrow | \ndecrease star rating | \n
评分组件通常用于用户反馈场景。
\n参数 | \n说明 | \n类型 | \n默认值 | \n
---|---|---|---|
defaultValue | \n默认值 | \nNumber | \n0 | \n
size | \n尺寸 可选值: 'small', 'medium', 'large' | \nEnum | \n'medium' | \n
value | \n值 | \nNumber | \n- | \n
count | \n评分的总数 | \nNumber | \n5 | \n
showGrade | \n是否显示 grade | \nBoolean | \nfalse | \n
allowHalf | \n是否允许半星评分 | \nBoolean | \nfalse | \n
onChange | \n用户点击评分时触发的回调 签名: Function(value: String) => void 参数: value: {String} 评分值 | \nFunction | \nfunc.noop | \n
onHoverChange | \n用户hover评分时触发的回调 签名: Function(value: String) => void 参数: value: {String} 评分值 | \nFunction | \nfunc.noop | \n
disabled | \n是否禁用 | \nBoolean | \nfalse | \n
readAs | \n评分文案生成方法,传入id支持无障碍时,读屏软件可读 签名: Function() => void | \nFunction | \nval => val | \n
按键 | \n说明 | \n
---|---|
Up Arrow | \n增加星级评分 | \n
Down Arrow | \n减少星级评分 | \n
Right Arrow | \n增加星级评分 | \n
Left Arrow | \n减少星级评分 | \n
Press the Enter key to call the onSearch
event handle,Please refer to ARIA and KeyBoard
.
import { Search } from '@alifd/next';\n\nReactDOM.render(<div>\n <Search key=\"3\" placeholder=\"Please enter the search content\" onSearch={v => console.log(v)} searchText={<span>search</span>} style={{width: '400px'}}/>\n</div>, mountNode);
按下Enter键调用onSearch
事件去处理,请参考ARIA and KeyBoard
。
import { Search } from '@alifd/next';\n\nReactDOM.render(<div>\n <Search key=\"3\" placeholder=\"Please enter the search content\" onSearch={v => console.log(v)} searchText={<span>search</span>} style={{width: '400px'}}/>\n</div>, mountNode);
simple
,\ndefault
,\ncustom text
,\ncustom text widthout icon
,\nsimple
,\ndefault
,\ncustom text
,\ncustom text widthout icon
,\nimport { Search } from '@alifd/next';\n\n\nfunction onSearch(v) {\n console.log(v);\n}\nconst App = () => [\n <p key=\"1\">simple</p>,\n <Search key=\"2\" shape=\"simple\" onSearch={onSearch} style={{width: '400px'}}/>,\n <p key=\"3\">default</p>,\n <Search key=\"4\" onSearch={onSearch} style={{width: '400px'}}/>,\n <p key=\"5\">custom text </p>,\n <Search key=\"6\" searchText=\"search\" onSearch={onSearch} style={{width: '400px'}}/>,\n <p key=\"7\">custom text widthout icon</p>,\n <Search key=\"8\" hasIcon={false} searchText={<span style={{color: 'blue'}}>search</span>} onSearch={onSearch} style={{width: '400px'}}/>\n];\n\nReactDOM.render(<App />, mountNode);
simple
,\ndefault
,\ncustom text
,\ncustom text widthout icon
,\nsimple
,\ndefault
,\ncustom text
,\ncustom text widthout icon
,\nimport { Search } from '@alifd/next';\n\n\nfunction onSearch(v) {\n console.log(v);\n}\nconst App = () => [\n <p key=\"1\">simple</p>,\n <Search key=\"2\" shape=\"simple\" onSearch={onSearch} style={{width: '400px'}}/>,\n <p key=\"3\">default</p>,\n <Search key=\"4\" onSearch={onSearch} style={{width: '400px'}}/>,\n <p key=\"5\">custom text </p>,\n <Search key=\"6\" searchText=\"search\" onSearch={onSearch} style={{width: '400px'}}/>,\n <p key=\"7\">custom text widthout icon</p>,\n <Search key=\"8\" hasIcon={false} searchText={<span style={{color: 'blue'}}>search</span>} onSearch={onSearch} style={{width: '400px'}}/>\n];\n\nReactDOM.render(<App />, mountNode);
import { Search } from '@alifd/next';\n\nconst dataSource = [{\n label: 'Recent',\n value: 'Recent'\n}, {\n label: 'dress',\n value: 'dress'\n}, {\n label: 'sunglasses',\n value: 'sunglasses'\n}, {\n label: 't-shirt',\n value: 't-shirt'\n}];\n\nclass App extends React.Component {\n onSearch(value, filterValue) {\n console.log(value, filterValue);\n }\n\n onChange(value) {\n this.setState({\n value: value\n });\n }\n\n render() {\n return (\n <Search dataSource={dataSource} onChange={this.onChange.bind(this)}\n onSearch={this.onSearch.bind(this)}/>\n );\n }\n}\n\nReactDOM.render(<App/>, mountNode);
import { Search } from '@alifd/next';\n\nconst dataSource = [{\n label: 'Recent',\n value: 'Recent'\n}, {\n label: 'dress',\n value: 'dress'\n}, {\n label: 'sunglasses',\n value: 'sunglasses'\n}, {\n label: 't-shirt',\n value: 't-shirt'\n}];\n\nclass App extends React.Component {\n onSearch(value, filterValue) {\n console.log(value, filterValue);\n }\n\n onChange(value) {\n this.setState({\n value: value\n });\n }\n\n render() {\n return (\n <Search dataSource={dataSource} onChange={this.onChange.bind(this)}\n onSearch={this.onSearch.bind(this)}/>\n );\n }\n}\n\nReactDOM.render(<App/>, mountNode);
custom dropdown content
\n","order":"5"},"codes":{"jsx":"import { Search, Menu, Button } from '@alifd/next';\n\nconst menuData = [\n {\n label: 'Option 1',\n value: 'Option 1 Value',\n index: '1'\n }, {\n label: 'Option 2',\n value: 'Option 2 Value',\n index: '2'\n }, {\n label: 'Option 3',\n value: 'Option 3 Value',\n index: '3'\n }, {\n label: 'Option 4',\n value: 'Option 4 Value',\n index: '4'\n }\n];\n\nclass App extends React.Component {\n constructor(props) {\n super(props);\n this.state = {\n visible: false,\n value: '111222',\n menuData: menuData\n };\n\n this.onVisibleChange = this.onVisibleChange.bind(this);\n this.onSearch = this.onSearch.bind(this);\n this.onChange = this.onChange.bind(this);\n this.onFocus = this.onFocus.bind(this);\n }\n\n renderMenu() {\n const menuData = this.state.menuData;\n\n return ();\n }\n\n onSearch(value) {\n console.log(value);\n }\n\n onChange(value) {\n this.setState({\n visible: value.length > 0,\n value: value\n });\n }\n\n onSelect(selectedKeys) {\n this.setState({\n visible: false,\n value: selectedKeys[0]\n });\n }\n\n onDelete(index, e) {\n e.stopPropagation();\n\n const menuData = this.state.menuData;\n\n const menuDataNew = [];\n\n menuData.forEach(function (item) {\n if (item.index !== index) {\n menuDataNew.push(item);\n }\n });\n\n this.setState({\n menuData: menuDataNew\n });\n }\n\n onFocus() {\n this.setState({\n visible: true\n });\n }\n\n onVisibleChange() {\n this.setState({\n visible: false\n });\n }\n\n render() {\n const {visible, value} = this.state;\n\n return (import { Search, Menu, Button } from '@alifd/next';\n\nconst menuData = [\n {\n label: 'Option 1',\n value: 'Option 1 Value',\n index: '1'\n }, {\n label: 'Option 2',\n value: 'Option 2 Value',\n index: '2'\n }, {\n label: 'Option 3',\n value: 'Option 3 Value',\n index: '3'\n }, {\n label: 'Option 4',\n value: 'Option 4 Value',\n index: '4'\n }\n];\n\nclass App extends React.Component {\n constructor(props) {\n super(props);\n this.state = {\n visible: false,\n value: '111222',\n menuData: menuData\n };\n\n this.onVisibleChange = this.onVisibleChange.bind(this);\n this.onSearch = this.onSearch.bind(this);\n this.onChange = this.onChange.bind(this);\n this.onFocus = this.onFocus.bind(this);\n }\n\n renderMenu() {\n const menuData = this.state.menuData;\n\n return (<Menu onSelect={this.onSelect.bind(this)} rtl className=\"diy-menu\" selectMode=\"single\">\n <Menu.Group label=\"Recent\" key=\"xxx\">\n {menuData.map((item) => {\n return (<Menu.Item key={item.value}>\n {item.label}\n <Button className=\"diy-menu-button\" onClick={this.onDelete.bind(this, item.index)} text>Delete</Button>\n </Menu.Item>);\n })}\n </Menu.Group>\n </Menu>);\n }\n\n onSearch(value) {\n console.log(value);\n }\n\n onChange(value) {\n this.setState({\n visible: value.length > 0,\n value: value\n });\n }\n\n onSelect(selectedKeys) {\n this.setState({\n visible: false,\n value: selectedKeys[0]\n });\n }\n\n onDelete(index, e) {\n e.stopPropagation();\n\n const menuData = this.state.menuData;\n\n const menuDataNew = [];\n\n menuData.forEach(function (item) {\n if (item.index !== index) {\n menuDataNew.push(item);\n }\n });\n\n this.setState({\n menuData: menuDataNew\n });\n }\n\n onFocus() {\n this.setState({\n visible: true\n });\n }\n\n onVisibleChange() {\n this.setState({\n visible: false\n });\n }\n\n render() {\n const {visible, value} = this.state;\n\n return (<div style={{width: 700}}>\n <Search\n onVisibleChange={this.onVisibleChange}\n popupContent={this.renderMenu()}\n visible={visible}\n value={value}\n onSearch={this.onSearch}\n onChange={this.onChange}\n onFocus={this.onFocus}\n />\n </div>);\n }\n}\n\nReactDOM.render(<App/>, mountNode);
\n.diy-menu{\n /*width: 275px*/;\n}\n\n.diy-menu .next-menu-item a{\n display:none;\n float: right;\n cursor: pointer;\n}\n.diy-menu .next-menu-item:hover a{\n display:inline-block;\n}\n.diy-menu .diy-menu-button {\n float: right;\n}\n.diy-menu[dir=rtl] .diy-menu-button {\n float: left;\n}
自定义下拉框内容。
\n","order":"5"},"codes":{"jsx":"import { Search, Menu, Button } from '@alifd/next';\n\nconst menuData = [\n {\n label: 'Option 1',\n value: 'Option 1 Value',\n index: '1'\n }, {\n label: 'Option 2',\n value: 'Option 2 Value',\n index: '2'\n }, {\n label: 'Option 3',\n value: 'Option 3 Value',\n index: '3'\n }, {\n label: 'Option 4',\n value: 'Option 4 Value',\n index: '4'\n }\n];\n\nclass App extends React.Component {\n constructor(props) {\n super(props);\n this.state = {\n visible: false,\n value: '111222',\n menuData: menuData\n };\n\n this.onVisibleChange = this.onVisibleChange.bind(this);\n this.onSearch = this.onSearch.bind(this);\n this.onChange = this.onChange.bind(this);\n this.onFocus = this.onFocus.bind(this);\n }\n\n renderMenu() {\n const menuData = this.state.menuData;\n\n return ();\n }\n\n onSearch(value) {\n console.log(value);\n }\n\n onChange(value) {\n this.setState({\n visible: value.length > 0,\n value: value\n });\n }\n\n onSelect(selectedKeys) {\n this.setState({\n visible: false,\n value: selectedKeys[0]\n });\n }\n\n onDelete(index, e) {\n e.stopPropagation();\n\n const menuData = this.state.menuData;\n\n const menuDataNew = [];\n\n menuData.forEach(function (item) {\n if (item.index !== index) {\n menuDataNew.push(item);\n }\n });\n\n this.setState({\n menuData: menuDataNew\n });\n }\n\n onFocus() {\n this.setState({\n visible: true\n });\n }\n\n onVisibleChange() {\n this.setState({\n visible: false\n });\n }\n\n render() {\n const {visible, value} = this.state;\n\n return (import { Search, Menu, Button } from '@alifd/next';\n\nconst menuData = [\n {\n label: 'Option 1',\n value: 'Option 1 Value',\n index: '1'\n }, {\n label: 'Option 2',\n value: 'Option 2 Value',\n index: '2'\n }, {\n label: 'Option 3',\n value: 'Option 3 Value',\n index: '3'\n }, {\n label: 'Option 4',\n value: 'Option 4 Value',\n index: '4'\n }\n];\n\nclass App extends React.Component {\n constructor(props) {\n super(props);\n this.state = {\n visible: false,\n value: '111222',\n menuData: menuData\n };\n\n this.onVisibleChange = this.onVisibleChange.bind(this);\n this.onSearch = this.onSearch.bind(this);\n this.onChange = this.onChange.bind(this);\n this.onFocus = this.onFocus.bind(this);\n }\n\n renderMenu() {\n const menuData = this.state.menuData;\n\n return (<Menu onSelect={this.onSelect.bind(this)} rtl className=\"diy-menu\" selectMode=\"single\">\n <Menu.Group label=\"Recent\" key=\"xxx\">\n {menuData.map((item) => {\n return (<Menu.Item key={item.value}>\n {item.label}\n <Button className=\"diy-menu-button\" onClick={this.onDelete.bind(this, item.index)} text>Delete</Button>\n </Menu.Item>);\n })}\n </Menu.Group>\n </Menu>);\n }\n\n onSearch(value) {\n console.log(value);\n }\n\n onChange(value) {\n this.setState({\n visible: value.length > 0,\n value: value\n });\n }\n\n onSelect(selectedKeys) {\n this.setState({\n visible: false,\n value: selectedKeys[0]\n });\n }\n\n onDelete(index, e) {\n e.stopPropagation();\n\n const menuData = this.state.menuData;\n\n const menuDataNew = [];\n\n menuData.forEach(function (item) {\n if (item.index !== index) {\n menuDataNew.push(item);\n }\n });\n\n this.setState({\n menuData: menuDataNew\n });\n }\n\n onFocus() {\n this.setState({\n visible: true\n });\n }\n\n onVisibleChange() {\n this.setState({\n visible: false\n });\n }\n\n render() {\n const {visible, value} = this.state;\n\n return (<div style={{width: 700}}>\n <Search\n onVisibleChange={this.onVisibleChange}\n popupContent={this.renderMenu()}\n visible={visible}\n value={value}\n onSearch={this.onSearch}\n onChange={this.onChange}\n onFocus={this.onFocus}\n />\n </div>);\n }\n}\n\nReactDOM.render(<App/>, mountNode);
\n.diy-menu{\n /*width: 275px*/;\n}\n\n.diy-menu .next-menu-item a{\n display:none;\n float: right;\n cursor: pointer;\n}\n.diy-menu .next-menu-item:hover a{\n display:inline-block;\n}\n.diy-menu .diy-menu-button {\n float: right;\n}\n.diy-menu[dir=rtl] .diy-menu-button {\n float: left;\n}
Filter dropdown, use with onFilterChange event
\n","order":"3"},"codes":{"jsx":"import { Search } from '@alifd/next';\n\nclass App extends React.Component {\n\n constructor(props) {\n super(props);\n this.state = {\n filter: [\n {\n label: 'Products',\n value: 'Products'\n },\n {\n label: 'Products1',\n value: 'Products1'\n },\n {\n label: 'Products2',\n value: 'Products2'\n },\n {\n label: 'Products3',\n value: 'Products3'\n },\n {\n label: 'Products4',\n value: 'Products4'\n },\n {\n label: 'Products5',\n value: 'Products5'\n },\n {\n label: 'Products6',\n value: 'Products6'\n },\n {\n label: 'Products7',\n value: 'Products7'\n },\n {\n label: 'Products8',\n value: 'Products8'\n },\n {\n label: 'Products9',\n value: 'Products9'\n },\n {\n label: 'Products10',\n value: 'Products10'\n },\n {\n label: 'Suppliers',\n value: 'Suppliers',\n }\n ],\n value: ''\n };\n }\n\n onSearch(value, filterValue) {\n console.log(value, filterValue);\n }\n\n onChange(value) {\n this.setState({\n value: value\n });\n }\n\n // value is filter value,obj is the search value\n onFilterChange(value) {\n console.log(value);\n }\n\n render() {\n\n return (import { Search } from '@alifd/next';\n\nclass App extends React.Component {\n\n constructor(props) {\n super(props);\n this.state = {\n filter: [\n {\n label: 'Products',\n value: 'Products'\n },\n {\n label: 'Products1',\n value: 'Products1'\n },\n {\n label: 'Products2',\n value: 'Products2'\n },\n {\n label: 'Products3',\n value: 'Products3'\n },\n {\n label: 'Products4',\n value: 'Products4'\n },\n {\n label: 'Products5',\n value: 'Products5'\n },\n {\n label: 'Products6',\n value: 'Products6'\n },\n {\n label: 'Products7',\n value: 'Products7'\n },\n {\n label: 'Products8',\n value: 'Products8'\n },\n {\n label: 'Products9',\n value: 'Products9'\n },\n {\n label: 'Products10',\n value: 'Products10'\n },\n {\n label: 'Suppliers',\n value: 'Suppliers',\n }\n ],\n value: ''\n };\n }\n\n onSearch(value, filterValue) {\n console.log(value, filterValue);\n }\n\n onChange(value) {\n this.setState({\n value: value\n });\n }\n\n // value is filter value,obj is the search value\n onFilterChange(value) {\n console.log(value);\n }\n\n render() {\n\n return (<div>\n <Search onChange={this.onChange.bind(this)} onSearch={this.onSearch.bind(this)}\n filterProps={{autoWidth: false}} defaultFilterValue=\"Suppliers\"\n filter={this.state.filter} onFilterChange={this.onFilterChange.bind(this)}/>\n </div>);\n }\n}\n\nReactDOM.render(<App/>, mountNode);
带下拉框的用法。可以设置onFilterChange事件
\n","order":"3"},"codes":{"jsx":"import { Search } from '@alifd/next';\n\nclass App extends React.Component {\n\n constructor(props) {\n super(props);\n this.state = {\n filter: [\n {\n label: 'Products',\n value: 'Products'\n },\n {\n label: 'Products1',\n value: 'Products1'\n },\n {\n label: 'Products2',\n value: 'Products2'\n },\n {\n label: 'Products3',\n value: 'Products3'\n },\n {\n label: 'Products4',\n value: 'Products4'\n },\n {\n label: 'Products5',\n value: 'Products5'\n },\n {\n label: 'Products6',\n value: 'Products6'\n },\n {\n label: 'Products7',\n value: 'Products7'\n },\n {\n label: 'Products8',\n value: 'Products8'\n },\n {\n label: 'Products9',\n value: 'Products9'\n },\n {\n label: 'Products10',\n value: 'Products10'\n },\n {\n label: 'Suppliers',\n value: 'Suppliers',\n }\n ],\n value: ''\n };\n }\n\n onSearch(value, filterValue) {\n console.log(value, filterValue);\n }\n\n onChange(value) {\n this.setState({\n value: value\n });\n }\n\n // value is filter value,obj is the search value\n onFilterChange(value) {\n console.log(value);\n }\n\n render() {\n\n return (import { Search } from '@alifd/next';\n\nclass App extends React.Component {\n\n constructor(props) {\n super(props);\n this.state = {\n filter: [\n {\n label: 'Products',\n value: 'Products'\n },\n {\n label: 'Products1',\n value: 'Products1'\n },\n {\n label: 'Products2',\n value: 'Products2'\n },\n {\n label: 'Products3',\n value: 'Products3'\n },\n {\n label: 'Products4',\n value: 'Products4'\n },\n {\n label: 'Products5',\n value: 'Products5'\n },\n {\n label: 'Products6',\n value: 'Products6'\n },\n {\n label: 'Products7',\n value: 'Products7'\n },\n {\n label: 'Products8',\n value: 'Products8'\n },\n {\n label: 'Products9',\n value: 'Products9'\n },\n {\n label: 'Products10',\n value: 'Products10'\n },\n {\n label: 'Suppliers',\n value: 'Suppliers',\n }\n ],\n value: ''\n };\n }\n\n onSearch(value, filterValue) {\n console.log(value, filterValue);\n }\n\n onChange(value) {\n this.setState({\n value: value\n });\n }\n\n // value is filter value,obj is the search value\n onFilterChange(value) {\n console.log(value);\n }\n\n render() {\n\n return (<div>\n <Search onChange={this.onChange.bind(this)} onSearch={this.onSearch.bind(this)}\n filterProps={{autoWidth: false}} defaultFilterValue=\"Suppliers\"\n filter={this.state.filter} onFilterChange={this.onFilterChange.bind(this)}/>\n </div>);\n }\n}\n\nReactDOM.render(<App/>, mountNode);
Filter dropdown, use with onFilterChange.
\n","order":"2"},"codes":{"jsx":"import { Search } from '@alifd/next';\n\nReactDOM.render(import { Search } from '@alifd/next';\n\nReactDOM.render(<div>\n <Search\n size=\"large\"\n defaultValue=\"large\"\n searchText=\"Search\"\n placeholder=\"What are you looking for...\" />\n <br/><br/>\n <Search\n size=\"medium\"\n defaultValue=\"medium\"\n searchText=\"Search\"\n placeholder=\"What are you looking for...\" />\n</div>, mountNode);
通过size进行大小设置,支持large、medium
\n","order":"2"},"codes":{"jsx":"import { Search } from '@alifd/next';\n\nReactDOM.render(import { Search } from '@alifd/next';\n\nReactDOM.render(<div>\n <Search\n size=\"large\"\n defaultValue=\"large\"\n searchText=\"Search\"\n placeholder=\"What are you looking for...\" />\n <br/><br/>\n <Search\n size=\"medium\"\n defaultValue=\"medium\"\n searchText=\"Search\"\n placeholder=\"What are you looking for...\" />\n</div>, mountNode);
Simple Usage
\n","order":"1"},"codes":{"jsx":"import { Search } from '@alifd/next';\n\nReactDOM.render(import { Search } from '@alifd/next';\n\nReactDOM.render(<div>\n <h2>Normal</h2>\n <Search type=\"primary\" placeholder=\"primary\"/>\n <br/> <br/>\n <Search type=\"secondary\" placeholder=\"Secondary\"/>\n <br/> <br/>\n <Search type=\"normal\" placeholder=\"normal\"/>\n <br/> <br/>\n <div style={{background: '#333', padding: 20}}>\n <Search type=\"dark\" placeholder=\"dark\"/>\n </div>\n <h2>Simple</h2>\n <Search type=\"normal\" shape=\"simple\" placeholder=\"normal\"/>\n <br/> <br/>\n <div style={{background: '#333', padding: 20}}>\n <Search shape=\"simple\" type=\"dark\" placeholder=\"dark\"/>\n </div>\n</div>, mountNode);
简单用法
\n","order":"1"},"codes":{"jsx":"import { Search } from '@alifd/next';\n\nReactDOM.render(import { Search } from '@alifd/next';\n\nReactDOM.render(<div>\n <h2>Normal</h2>\n <Search type=\"primary\" placeholder=\"primary\"/>\n <br/> <br/>\n <Search type=\"secondary\" placeholder=\"Secondary\"/>\n <br/> <br/>\n <Search type=\"normal\" placeholder=\"normal\"/>\n <br/> <br/>\n <div style={{background: '#333', padding: 20}}>\n <Search type=\"dark\" placeholder=\"dark\"/>\n </div>\n <h2>Simple</h2>\n <Search type=\"normal\" shape=\"simple\" placeholder=\"normal\"/>\n <br/> <br/>\n <div style={{background: '#333', padding: 20}}>\n <Search shape=\"simple\" type=\"dark\" placeholder=\"dark\"/>\n </div>\n</div>, mountNode);
search data in forms or pages.
\n\n\nInhert from Select.AutoComplete, you can use AutoComplete api directly
\n
Param | \nDescripiton | \nType | \nDefault Value | \n
---|---|---|---|
size | \nsize option: 'large' 'medium' | \nEnum | \n'medium' | \n
type | \ntype. when shape=normal, type options: primary/secondary; when shape=simple, type options: normal/dark; option: 'primary', 'secondary', 'normal', 'dark' | \nEnum | \n'normal' | \n
shape | \nshape option: 'normal', 'simple' | \nEnum | \n'normal' | \n
defaultValue | \ndefault value | \nString | \n- | \n
value | \ncurrent value | \nString/Number | \n- | \n
onChange | \ncallback when value changes signature: Function() => void | \nFunction | \nfunc.noop | \n
onSearch | \ncallback when search button clicked signature: Function() => void | \nFunction | \nfunc.noop | \n
defaultFilterValue | \ndefault filter | \nString | \n- | \n
filter | \nfilter | \nArray | \n[] | \n
filterValue | \nfilter value | \nString | \n- | \n
onFilterChange | \ncallback when filter changes signature: Function() => void | \nFunction | \nfunc.noop | \n
dataSource | \ndropdown menu data source | \nArray | \n- | \n
placeholder | \ndefault hint | \nString | \n- | \n
searchText | \nbutton text | \nReactNode | \n- | \n
filterProps | \nfilter props | \nObject | \n- | \n
buttonProps | \nprops for Button | \nObject | \n{} | \n
popupContent | \ncustom popup menu | \nReactNode | \n- | \n
followTrigger | \nfollow Trigger or not | \nBoolean | \n- | \n
visible | \npopupContent is displayed | \nBoolean | \n- | \n
hasClear | \nshow clear text button | \nBoolean | \nfalse | \n
hasIcon | \nshow find button | \nBoolean | \ntrue | \n
disabled | \ndisabled or not | \nBoolean | \nfalse | \n
KeyBoard | \nDescripiton | \n
---|---|
Tab | \nTrigger the onSearch event | \n
页面、表单数据搜索时使用
\n\n\n输入框部分继承 Select.AutoComplete 的能力,可以直接用AutoComplete 的 api
\n
参数 | \n说明 | \n类型 | \n默认值 | \n
---|---|---|---|
size | \n大小 可选值: 'large'('大') 'medium'('小') | \nEnum | \n'medium' | \n
type | \n类型 shape=normal: primary/secondary; shape=simple: normal/dark; 可选值: 'primary', 'secondary', 'normal', 'dark' | \nEnum | \n'normal' | \n
shape | \n形状 可选值: 'normal', 'simple' | \nEnum | \n'normal' | \n
defaultValue | \n搜索框默认值 | \nString | \n- | \n
value | \n搜索框数值 | \nString/Number | \n- | \n
onChange | \n输入关键字时的回掉 签名: Function(value: Object) => void 参数: value: {Object} 输入值 | \nFunction | \nfunc.noop | \n
onSearch | \n点击搜索按钮触发的回调 签名: Function(value: String, filterValue: String) => void 参数: value: {String} 输入值 filterValue: {String} 选项值 | \nFunction | \nfunc.noop | \n
defaultFilterValue | \n选择器默认值 | \nString | \n- | \n
filter | \n选择器 | \nArray | \n[] | \n
filterValue | \n选择器值 | \nString | \n- | \n
onFilterChange | \n选择器发生变化时回调 签名: Function(filter: Object) => void 参数: filter: {Object} value | \nFunction | \nfunc.noop | \n
dataSource | \n搜索框下拉联想列表 | \nArray | \n- | \n
placeholder | \n默认提示 | \nString | \n- | \n
searchText | \nbutton 的内容 | \nReactNode | \n- | \n
filterProps | \n选择器的props | \nObject | \n- | \n
buttonProps | \n按钮的额外属性 | \nObject | \n{} | \n
popupContent | \n自定义渲染的的下拉框 | \nReactNode | \n- | \n
followTrigger | \n是否跟随滚动 | \nBoolean | \n- | \n
visible | \n自定义渲染的的下拉框 | \nBoolean | \n- | \n
hasClear | \n是否显示清除按钮 | \nBoolean | \nfalse | \n
hasIcon | \n是否显示搜索按钮 | \nBoolean | \ntrue | \n
disabled | \n是否禁用 | \nBoolean | \nfalse | \n
按键 | \n说明 | \n\n |
---|---|---|
Enter | \n触发onSearch事件 | \n
import { Select } from '@alifd/next';\n\nconst Option = Select.Option;\n\nclass App extends React.Component {\n constructor(props) {\n super(props);\n this.onChange = this.onChange.bind(this);\n }\n onChange(value) {\n console.log(value);\n };\n\n render() {\n return (<div>\n <span id=\"select-a11y\">Select: </span>\n <Select onChange={this.onChange} defaultValue=\"jack\" aria-labelledby=\"select-a11y\">\n <Option value=\"jack\">Jack</Option>\n <Option value=\"frank\">Frank</Option>\n <Option value=\"hugo\">Hugo</Option>\n </Select>\n </div>);\n }\n}\n\nReactDOM.render(<App />, mountNode);
当聚焦在组件上时,通过aria-labelledby
对组件进行描述。关于键盘操作请参考ARIA and KeyBoard
。
import { Select } from '@alifd/next';\n\nconst Option = Select.Option;\n\nclass App extends React.Component {\n constructor(props) {\n super(props);\n this.onChange = this.onChange.bind(this);\n }\n onChange(value) {\n console.log(value);\n };\n\n render() {\n return (<div>\n <span id=\"select-a11y\">Select: </span>\n <Select onChange={this.onChange} defaultValue=\"jack\" aria-labelledby=\"select-a11y\">\n <Option value=\"jack\">Jack</Option>\n <Option value=\"frank\">Frank</Option>\n <Option value=\"hugo\">Hugo</Option>\n </Select>\n </div>);\n }\n}\n\nReactDOM.render(<App />, mountNode);
simple usage
\n","order":"0"},"codes":{"jsx":"import { Select } from '@alifd/next';\n\nconst Option = Select.Option;\n\nconst onChange = function (value) {\n console.log(value);\n};\nconst onBlur = function (e) {\n console.log(/onblur/,e);\n};\n\nconst onToggleHighlightItem = function (item, type) {\n console.log(item, type);\n};\n\nReactDOM.render(, mountNode);\n"},"body":"\n````jsx\nimport { Select } from '@alifd/next';\n\nconst Option = Select.Option;\n\nconst onChange = function (value) {\n console.log(value);\n};\nconst onBlur = function (e) {\n console.log(/onblur/,e);\n};\n\nconst onToggleHighlightItem = function (item, type) {\n console.log(item, type);\n};\n\nReactDOM.render(, mountNode);\n````","html":"import { Select } from '@alifd/next';\n\nconst Option = Select.Option;\n\nconst onChange = function (value) {\n console.log(value);\n};\nconst onBlur = function (e) {\n console.log(/onblur/,e);\n};\n\nconst onToggleHighlightItem = function (item, type) {\n console.log(item, type);\n};\n\nReactDOM.render(<Select id=\"basic-demo\" onChange={onChange} onBlur={onBlur} onToggleHighlightItem={onToggleHighlightItem} defaultValue=\"jack\" aria-label=\"name is\" showSearch hasClear>\n <Option value=\"jack\">Jack</Option>\n <Option value=\"frank\">Frank</Option>\n <Option value=\"hugo\">Hugo</Option>\n</Select>, mountNode);
简单
\n","order":"0"},"codes":{"jsx":"import { Select } from '@alifd/next';\n\nconst Option = Select.Option;\n\nconst onChange = function (value) {\n console.log(value);\n};\nconst onBlur = function (e) {\n console.log(/onblur/,e);\n};\n\nconst onToggleHighlightItem = function (item, type) {\n console.log(item, type);\n};\n\nReactDOM.render(, mountNode);\n"},"body":"\n\n````jsx\nimport { Select } from '@alifd/next';\n\nconst Option = Select.Option;\n\nconst onChange = function (value) {\n console.log(value);\n};\nconst onBlur = function (e) {\n console.log(/onblur/,e);\n};\n\nconst onToggleHighlightItem = function (item, type) {\n console.log(item, type);\n};\n\nReactDOM.render(, mountNode);\n````","html":"import { Select } from '@alifd/next';\n\nconst Option = Select.Option;\n\nconst onChange = function (value) {\n console.log(value);\n};\nconst onBlur = function (e) {\n console.log(/onblur/,e);\n};\n\nconst onToggleHighlightItem = function (item, type) {\n console.log(item, type);\n};\n\nReactDOM.render(<Select id=\"basic-demo\" onChange={onChange} onBlur={onBlur} onToggleHighlightItem={onToggleHighlightItem} defaultValue=\"jack\" aria-label=\"name is\" showSearch hasClear>\n <Option value=\"jack\">Jack</Option>\n <Option value=\"frank\">Frank</Option>\n <Option value=\"hugo\">Hugo</Option>\n</Select>, mountNode);
AutoComplete
api of size/disabled/hasClear
import { Select } from '@alifd/next';\n\nconst {AutoComplete} = Select;\nconst dataSource = [\n 'Lucy King',\n 'Lily King',\n 'Jim Green',\n {\n label: 'Chinese',\n children: [\n {value: 'Hang Meimei', label: 'Hang Meimei'},\n 'Li Lei',\n {value: 'Gao Hui', label: 'Gao Hui', disabled: true},\n 'Zhang San',\n 'Li Si',\n 'Wang Wu',\n {value: 'Zhao Benshan', label: 'Zhao Benshan', disabled: true},\n 'Sun Yang',\n 'Song Shuying'\n ]\n },\n {\n label: 'Pets',\n children: [\n 'Poly',\n 'Kitty'\n ]\n }\n];\n\nconst ctrlDataSources = {\n size: ['small', 'medium', 'large'],\n disabled: [true, false],\n hasClear: [true, false]\n};\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n value: null,\n size: undefined,\n disabled: undefined,\n hasClear: undefined\n };\n\n this.handleChange = this.handleChange.bind(this);\n this.handleCtrlChange = this.handleCtrlChange.bind(this);\n }\n\n handleCtrlChange(key, value) {\n this.setState({[key]: value});\n\n if (key === 'mode') {\n this.setState({value: null});\n }\n }\n\n handleChange(value) {\n console.log('handleChange: value: ', value);\n this.setState({value});\n }\n\n renderCtrlNodes(state) {\n const ctrlNodes = [];\n let k;\n for (k in ctrlDataSources) {\n if (ctrlDataSources.hasOwnProperty(k)) {\n ctrlNodes.push(\n <Select key={k}\n label={`${k}: `}\n value={state[k]}\n dataSource={ctrlDataSources[k]}\n onChange={this.handleCtrlChange.bind(this, k)} />\n );\n }\n }\n\n return ctrlNodes;\n }\n\n render() {\n\n return (\n <div className=\"demo-container\">\n <div className=\"demo-controller\">{this.renderCtrlNodes(this.state)}</div>\n <AutoComplete\n {...this.state}\n style={{maxWidth: 300}}\n onChange={this.handleChange}\n dataSource={dataSource} />\n </div>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
.demo-container {\n padding: 16px;\n background-color: #F8F8F8;\n}\n\n.demo-controller {\n padding: 12px 12px 4px;\n margin-bottom: 16px;\n border: 2px dashed #ddd;\n}\n\n.next-select {\n margin-right: 8px;\n margin-bottom: 8px;\n}
AutoComplete
大小、disabled、清除
import { Select } from '@alifd/next';\n\nconst {AutoComplete} = Select;\nconst dataSource = [\n 'Lucy King',\n 'Lily King',\n 'Jim Green',\n {\n label: 'Chinese',\n children: [\n {value: 'Hang Meimei', label: 'Hang Meimei'},\n 'Li Lei',\n {value: 'Gao Hui', label: 'Gao Hui', disabled: true},\n 'Zhang San',\n 'Li Si',\n 'Wang Wu',\n {value: 'Zhao Benshan', label: 'Zhao Benshan', disabled: true},\n 'Sun Yang',\n 'Song Shuying'\n ]\n },\n {\n label: 'Pets',\n children: [\n 'Poly',\n 'Kitty'\n ]\n }\n];\n\nconst ctrlDataSources = {\n size: ['small', 'medium', 'large'],\n disabled: [true, false],\n hasClear: [true, false]\n};\n\nclass Demo extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n value: null,\n size: undefined,\n disabled: undefined,\n hasClear: undefined\n };\n\n this.handleChange = this.handleChange.bind(this);\n this.handleCtrlChange = this.handleCtrlChange.bind(this);\n }\n\n handleCtrlChange(key, value) {\n this.setState({[key]: value});\n\n if (key === 'mode') {\n this.setState({value: null});\n }\n }\n\n handleChange(value) {\n console.log('handleChange: value: ', value);\n this.setState({value});\n }\n\n renderCtrlNodes(state) {\n const ctrlNodes = [];\n let k;\n for (k in ctrlDataSources) {\n if (ctrlDataSources.hasOwnProperty(k)) {\n ctrlNodes.push(\n <Select key={k}\n label={`${k}: `}\n value={state[k]}\n dataSource={ctrlDataSources[k]}\n onChange={this.handleCtrlChange.bind(this, k)} />\n );\n }\n }\n\n return ctrlNodes;\n }\n\n render() {\n\n return (\n <div className=\"demo-container\">\n <div className=\"demo-controller\">{this.renderCtrlNodes(this.state)}</div>\n <AutoComplete\n {...this.state}\n style={{maxWidth: 300}}\n onChange={this.handleChange}\n dataSource={dataSource} />\n </div>\n );\n }\n}\n\nReactDOM.render(<Demo />, mountNode);
.demo-container {\n padding: 16px;\n background-color: #F8F8F8;\n}\n\n.demo-controller {\n padding: 12px 12px 4px;\n margin-bottom: 16px;\n border: 2px dashed #ddd;\n}\n\n.next-select {\n margin-right: 8px;\n margin-bottom: 8px;\n}
By set filterLocal
to false, so you can use AutoComplete with dynamic data.
import { Select } from '@alifd/next';\nimport jsonp from 'jsonp';\n\nconst {AutoComplete} = Select;\n\nclass Demo extends React.Component {\n state = {\n dataSource: []\n };\n\n handleChange = value => {\n clearTimeout(this.searchTimeout);\n this.searchTimeout = setTimeout(() => {\n // eslint-disable-next-line handle-callback-err\n jsonp(`https://suggest.taobao.com/sug?code=utf-8&q=${value}`, (err, data) => {\n const dataSource = data.result.map(item => item[0]);\n this.setState({dataSource});\n });\n }, 100);\n }\n\n render() {\n return (\n <div className=\"demo-container\">\n <AutoComplete\n filterLocal={false}\n placeholder=\"search from taobao\"\n onChange={this.handleChange}\n dataSource={this.state.dataSource}/>\n </div>\n );\n }\n}\n\nReactDOM.render(<Demo/>, mountNode);
.demo-container {\n background-color: #F8F8F8;\n padding: 16px;\n}
使用动态数据填充 AutoComplete, 设置 filterLocal
为 false
import { Select } from '@alifd/next';\nimport jsonp from 'jsonp';\n\nconst {AutoComplete} = Select;\n\nclass Demo extends React.Component {\n state = {\n dataSource: []\n };\n\n handleChange = value => {\n clearTimeout(this.searchTimeout);\n this.searchTimeout = setTimeout(() => {\n // eslint-disable-next-line handle-callback-err\n jsonp(`https://suggest.taobao.com/sug?code=utf-8&q=${value}`, (err, data) => {\n const dataSource = data.result.map(item => item[0]);\n this.setState({dataSource});\n });\n }, 100);\n }\n\n render() {\n return (\n <div className=\"demo-container\">\n <AutoComplete\n filterLocal={false}\n placeholder=\"search from taobao\"\n onChange={this.handleChange}\n dataSource={this.state.dataSource}/>\n </div>\n );\n }\n}\n\nReactDOM.render(<Demo/>, mountNode);
.demo-container {\n background-color: #F8F8F8;\n padding: 16px;\n}
menu with pictures
\n","order":"12"},"codes":{"jsx":"import { Select, Icon } from '@alifd/next';\nimport jsonp from 'jsonp';\n\nconst {AutoComplete} = Select;\n\nclass Demo extends React.Component {\n state = {\n dataSource: []\n }\n\n handleChange = (value) => {\n if (this.searchTimeout) {\n clearTimeout(this.searchTimeout);\n }\n this.searchTimeout = setTimeout(() => {\n // eslint-disable-next-line handle-callback-err\n jsonp(`https://suggest.taobao.com/sug?code=utf-8&q=${value}`, (err, data) => {\n const dataSource = data.result.map(item => {\n return {\n label:import { Select, Icon } from '@alifd/next';\nimport jsonp from 'jsonp';\n\nconst {AutoComplete} = Select;\n\nclass Demo extends React.Component {\n state = {\n dataSource: []\n }\n\n handleChange = (value) => {\n if (this.searchTimeout) {\n clearTimeout(this.searchTimeout);\n }\n this.searchTimeout = setTimeout(() => {\n // eslint-disable-next-line handle-callback-err\n jsonp(`https://suggest.taobao.com/sug?code=utf-8&q=${value}`, (err, data) => {\n const dataSource = data.result.map(item => {\n return {\n label: <div><Icon type=\"picture\" size=\"small\"/> {item[0]}</div>,\n value: item[1],\n originLabel: item[0]\n };\n });\n this.setState({dataSource});\n });\n }, 100);\n }\n\n render() {\n return (\n <div className=\"demo-container\">\n <AutoComplete onChange={this.handleChange}\n filterLocal={false}\n fillProps=\"originLabel\"\n placeholder=\"search from taobao\"\n dataSource={this.state.dataSource}/></div>\n );\n }\n}\nReactDOM.render(<Demo/>, mountNode);
.next-select {\n margin-right:10px;\n vertical-align: middle;\n}\n\n.demo-container {\n background-color: #F8F8F8;\n padding: 16px;\n}\n\n.demo-container p {\n margin-top:0;\n}
展示较为复杂的内容展示
\n","order":"12"},"codes":{"jsx":"import { Select, Icon } from '@alifd/next';\nimport jsonp from 'jsonp';\n\nconst {AutoComplete} = Select;\n\nclass Demo extends React.Component {\n state = {\n dataSource: []\n }\n\n handleChange = (value) => {\n if (this.searchTimeout) {\n clearTimeout(this.searchTimeout);\n }\n this.searchTimeout = setTimeout(() => {\n // eslint-disable-next-line handle-callback-err\n jsonp(`https://suggest.taobao.com/sug?code=utf-8&q=${value}`, (err, data) => {\n const dataSource = data.result.map(item => {\n return {\n label:import { Select, Icon } from '@alifd/next';\nimport jsonp from 'jsonp';\n\nconst {AutoComplete} = Select;\n\nclass Demo extends React.Component {\n state = {\n dataSource: []\n }\n\n handleChange = (value) => {\n if (this.searchTimeout) {\n clearTimeout(this.searchTimeout);\n }\n this.searchTimeout = setTimeout(() => {\n // eslint-disable-next-line handle-callback-err\n jsonp(`https://suggest.taobao.com/sug?code=utf-8&q=${value}`, (err, data) => {\n const dataSource = data.result.map(item => {\n return {\n label: <div><Icon type=\"picture\" size=\"small\"/> {item[0]}</div>,\n value: item[1],\n originLabel: item[0]\n };\n });\n this.setState({dataSource});\n });\n }, 100);\n }\n\n render() {\n return (\n <div className=\"demo-container\">\n <AutoComplete onChange={this.handleChange}\n filterLocal={false}\n fillProps=\"originLabel\"\n placeholder=\"search from taobao\"\n dataSource={this.state.dataSource}/></div>\n );\n }\n}\nReactDOM.render(<Demo/>, mountNode);
.next-select {\n margin-right:10px;\n vertical-align: middle;\n}\n\n.demo-container {\n background-color: #F8F8F8;\n padding: 16px;\n}\n\n.demo-container p {\n margin-top:0;\n}
AutoComplete
inherits the capabilities of Input
and adds autoComplete functionality to it.
import { Select } from '@alifd/next';\n\nconst dataSource = [\n 'Lucy King',\n 'Lily King',\n 'Jim Green',\n {\n label: 'Chinese',\n children: [\n {value: 'Hang Meimei', label: 'Hang Meimei'},\n 'Li Lei',\n {value: 'Gao Hui', label: 'Gao Hui', disabled: true},\n 'Zhang San',\n 'Li Si',\n 'Wang Wu',\n {value: 'Zhao Benshan', label: 'Zhao Benshan', disabled: true},\n 'Sun Yang',\n 'Song Shuying'\n ]\n },\n {\n label: 'Pets',\n children: [\n 'Poly',\n 'Kitty'\n ]\n }\n];\n\nconst onChange = (v) => {\n console.log(v);\n};\n\nReactDOM.render(<Select.AutoComplete style={{width: 300}} onChange={onChange} dataSource={dataSource} />, mountNode);
AutoComplete
继承了 Input
的能力,并在其基础上增加了 autoComplete 的功能。\n对于设置为AutoComplete
为off不生效对的情况,可以参考 MDN 中进行设置。
import { Select } from '@alifd/next';\n\nconst dataSource = [\n 'Lucy King',\n 'Lily King',\n 'Jim Green',\n {\n label: 'Chinese',\n children: [\n {value: 'Hang Meimei', label: 'Hang Meimei'},\n 'Li Lei',\n {value: 'Gao Hui', label: 'Gao Hui', disabled: true},\n 'Zhang San',\n 'Li Si',\n 'Wang Wu',\n {value: 'Zhao Benshan', label: 'Zhao Benshan', disabled: true},\n 'Sun Yang',\n 'Song Shuying'\n ]\n },\n {\n label: 'Pets',\n children: [\n 'Poly',\n 'Kitty'\n ]\n }\n];\n\nconst onChange = (v) => {\n console.log(v);\n};\n\nReactDOM.render(<Select.AutoComplete style={{width: 300}} onChange={onChange} dataSource={dataSource} />, mountNode);
custom render Item by api of itemRender
and valueRender
(only support by Select)
import { Select, Icon } from '@alifd/next';\n\nconst dataSource = [\n {value: '#FF0000', label: 'red', title: 'red'},\n {value: '#00AA00', label: 'green', title: 'green'},\n {value: '#B482DB', label: 'purple', title: 'purple'},\n {value: '#F17334', label: 'orange', title: 'orange'},\n {value: '#66CCFF', label: 'blue', title: 'blue'}\n];\n\nconst itemRender = item => {\n return (\n <span>\n <Icon type=\"account\" size=\"xs\" style={{color: item.value}} />\n <Icon type=\"account\" size=\"xs\" style={{color: item.value}} />\n <Icon type=\"account\" size=\"xs\" style={{color: item.value}} />\n <Icon type=\"account\" size=\"xs\" style={{color: item.value}} />\n <Icon type=\"account\" size=\"xs\" style={{color: item.value}} />\n </span>\n );\n};\n\nconst valueRender = item => {\n return <span><Icon type=\"account\" size=\"xs\" style={{color: item.value}} /> {item.label}</span>;\n};\n\nconst dataSource2 = [\n 'Lorem ipsum dolor sit amet',\n 'consectetur adipisicing elit',\n 'sed do eiusmod tempor incididunt',\n 'ut labore et dolore magna aliqua.',\n 'Ut enim ad minim veniam',\n 'quis nostrud exercitation',\n 'ullamco laboris nisi ut',\n 'aliquip ex ea commodo consequat',\n 'Duis aute irure dolor in',\n 'reprehenderit in voluptate',\n 'velit esse cillum dolore eu',\n 'Fugiat nulla pariatur excepteur sint',\n 'occaecat cupidatat non proident',\n 'sunt in culpa qui officia',\n 'deserunt mollit anim id est laborum'\n];\n\n// highlight keywords\nconst itemRender2 = (item, searchKey) => {\n let label = item.label;\n if (searchKey && searchKey.length) {\n const key = searchKey.replace(/[-/\\\\^$*+?.()|[\\]{}]/g, '\\\\$&');\n const reg = new RegExp(`(${key})`, 'ig');\n label = label.replace(reg, x => `<span class=\"next-select-highlight\">${x}</span>`);\n }\n\n return <span dangerouslySetInnerHTML={{__html: label}} />;\n};\n\nReactDOM.render(\n <div className=\"demo-container\">\n <Select dataSource={dataSource} itemRender={itemRender} valueRender={valueRender} placeholder=\"pick your color\" />\n <Select showSearch dataSource={dataSource2} itemRender={itemRender2} placeholder=\"highlight keywords\" style={{minWidth: 200}} />\n </div>,\n mountNode\n);
.demo-container {\n padding: 16px;\n background-color: #F8F8F8;\n}\n\n.demo-container .next-select {\n margin-right: 10px;\n}
通过 itemRender
和 valueRender
(仅 Select) 自定义渲染的节点内容。
import { Select, Icon } from '@alifd/next';\n\nconst dataSource = [\n {value: '#FF0000', label: 'red', title: 'red'},\n {value: '#00AA00', label: 'green', title: 'green'},\n {value: '#B482DB', label: 'purple', title: 'purple'},\n {value: '#F17334', label: 'orange', title: 'orange'},\n {value: '#66CCFF', label: 'blue', title: 'blue'}\n];\n\nconst itemRender = item => {\n return (\n <span>\n <Icon type=\"account\" size=\"xs\" style={{color: item.value}} />\n <Icon type=\"account\" size=\"xs\" style={{color: item.value}} />\n <Icon type=\"account\" size=\"xs\" style={{color: item.value}} />\n <Icon type=\"account\" size=\"xs\" style={{color: item.value}} />\n <Icon type=\"account\" size=\"xs\" style={{color: item.value}} />\n </span>\n );\n};\n\nconst valueRender = item => {\n return <span><Icon type=\"account\" size=\"xs\" style={{color: item.value}} /> {item.label}</span>;\n};\n\nconst dataSource2 = [\n 'Lorem ipsum dolor sit amet',\n 'consectetur adipisicing elit',\n 'sed do eiusmod tempor incididunt',\n 'ut labore et dolore magna aliqua.',\n 'Ut enim ad minim veniam',\n 'quis nostrud exercitation',\n 'ullamco laboris nisi ut',\n 'aliquip ex ea commodo consequat',\n 'Duis aute irure dolor in',\n 'reprehenderit in voluptate',\n 'velit esse cillum dolore eu',\n 'Fugiat nulla pariatur excepteur sint',\n 'occaecat cupidatat non proident',\n 'sunt in culpa qui officia',\n 'deserunt mollit anim id est laborum'\n];\n\n// highlight keywords\nconst itemRender2 = (item, searchKey) => {\n let label = item.label;\n if (searchKey && searchKey.length) {\n const key = searchKey.replace(/[-/\\\\^$*+?.()|[\\]{}]/g, '\\\\$&');\n const reg = new RegExp(`(${key})`, 'ig');\n label = label.replace(reg, x => `<span class=\"next-select-highlight\">${x}</span>`);\n }\n\n return <span dangerouslySetInnerHTML={{__html: label}} />;\n};\n\nReactDOM.render(\n <div className=\"demo-container\">\n <Select dataSource={dataSource} itemRender={itemRender} valueRender={valueRender} placeholder=\"pick your color\" />\n <Select showSearch dataSource={dataSource2} itemRender={itemRender2} placeholder=\"highlight keywords\" style={{minWidth: 200}} />\n </div>,\n mountNode\n);
.demo-container {\n padding: 16px;\n background-color: #F8F8F8;\n}\n\n.demo-container .next-select {\n margin-right: 10px;\n}
custom Popup by popupContent